[英]C# CustomAttributeData class to attribute
我在Swashbuckle.Swagger.IOperationFilter
類中有以下代碼。
List<CustomAttributeData> controllerAttributes = apiDescription
.ActionDescriptor
.ControllerDescriptor
.ControllerType
.CustomAttributes
.Where(a => a.AttributeType == typeof(SwaggerFileInFormDataAttribute))
.ToList();
我正在成功獲取集合。 我想將集合List<CustomAttributeData>
轉換為我的自定義屬性List<SwaggerFileInFormDataAttribute>
的集合。
我想將System.Reflection.CustomAttributeData
類轉換為我的自定義屬性SwaggerFileInFormDataAttribute
。
編輯1:
這是我的SwaggerFileInFormDataAttribute
屬性的樣子。
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class SwaggerFileInFormDataAttribute : Attribute
{
private ICollection<string> displayNames;
public SwaggerFileInFormDataAttribute()
{
this.DisplayNames = new List<string> { "File" };
}
public SwaggerFileInFormDataAttribute(params string[] displayNames)
{
this.DisplayNames = displayNames;
}
public ICollection<string> DisplayNames
{
get
{
if (this.displayNames == null)
return new List<string> { "File" };
else
return this.displayNames;
}
set => displayNames = value;
}
}
將List<CustomAttributeData>
成功轉換為List<SwaggerFileInFormDataAttribute>
我將使用名為DisplayNames
SwaggerFileInFormDataAttribute
類中顯示的屬性。
List<SwaggerFileInFormDataAttribute> customControllerAttributes = apiDescription
.ActionDescriptor
.ControllerDescriptor
.ControllerType
.CustomAttributes
.Where(a => a.AttributeType == typeof(SwaggerFileInFormDataAttribute))
.Select(a =>
{
ReadOnlyCollection<CustomAttributeTypedArgument> costuctorArgumentsReadOnlyCollection = (ReadOnlyCollection<CustomAttributeTypedArgument>)a.ConstructorArguments.Select(x => x.Value).FirstOrDefault();
string[] contructorParams = costuctorArgumentsReadOnlyCollection?.ToArray().Select(x => x.Value.ToString()).ToArray();
SwaggerFileInFormDataAttribute myCustomAttr = (SwaggerFileInFormDataAttribute)Activator.CreateInstance(a.AttributeType, contructorParams);
return myCustomAttr;
})
.ToList();
說明:如果所需屬性的構造函數為空,則可以跳過兩個變量costuctorArgumentsReadOnlyCollection
和contructorParams
。
在這種情況下,只有這一行就足夠了:
(SwaggerFileInFormDataAttribute)Activator.CreateInstance(a.AttributeType, null);
這是一個更清潔的解決方案。 我們可以像這樣完全跳過IOperationFilter
的CustomAttributeData
類:
List<SwaggerFileInFormDataAttribute> controllerAttributes = apiDescription
.ActionDescriptor
.ControllerDescriptor
.GetCustomAttributes<SwaggerFileInFormDataAttribute>()
.ToList();
在您的.Where
,根據需要添加選擇和翻譯。 最簡單的方法是,在您的自定義類中,創建一個將SwaggerFileInFormDataAttribute
作為參數並根據需要映射到您的自定義類的構造函數。 那么你的Select
將是:
.Where(a => a.AttributeType == typeof(SwaggerFileInFormDataAttribute))
.Select(a => new CustomAttributeData(a))
.ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.