G.D*_*mov 5 c# reflection attributes .net-4.8
我在一个类中有以下代码Swashbuckle.Swagger.IOperationFilter。
List<CustomAttributeData> controllerAttributes = apiDescription
.ActionDescriptor
.ControllerDescriptor
.ControllerType
.CustomAttributes
.Where(a => a.AttributeType == typeof(SwaggerFileInFormDataAttribute))
.ToList();
Run Code Online (Sandbox Code Playgroud)
我正在成功获取该集合。我想将集合转换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;
}
}
Run Code Online (Sandbox Code Playgroud)
成功将 转换为 后,List<CustomAttributeData>我将使用名为 的List<SwaggerFileInFormDataAttribute>类中显示的属性。SwaggerFileInFormDataAttributeDisplayNames
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();
Run Code Online (Sandbox Code Playgroud)
说明:如果所需属性具有空构造函数,则可以跳过变量costuctorArgumentsReadOnlyCollection和。contructorParams
在这种情况下,只有这一行就足够了:
(SwaggerFileInFormDataAttribute)Activator.CreateInstance(a.AttributeType, null);
这是一个更干净的解决方案。我们可以CustomAttributeData像IOperationFilter这样完全跳过课程:
List<SwaggerFileInFormDataAttribute> controllerAttributes = apiDescription
.ActionDescriptor
.ControllerDescriptor
.GetCustomAttributes<SwaggerFileInFormDataAttribute>()
.ToList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3461 次 |
| 最近记录: |