C# 自定义属性的typeof(类)的等效项
对于自定义属性是否有一个等价的C# 自定义属性的typeof(类)的等效项,c#,attributes,custom-attributes,C#,Attributes,Custom Attributes,对于自定义属性是否有一个等价的typeof() 具体地说,我想以一种不依赖字符串比较的方式重写这段代码 if (prop.GetCustomAttributes(true).Any(c => c.GetType().Name == "JsonIgnoreAttribute")) { ... } 使用typeof()有什么问题?或者更好的是,是 if (prop.GetCustomAttributes(true).Any(c => c is JsonIgnoreAttribute))
typeof()
具体地说,我想以一种不依赖字符串比较的方式重写这段代码
if (prop.GetCustomAttributes(true).Any(c => c.GetType().Name == "JsonIgnoreAttribute")) { ... }
使用
typeof()
有什么问题?或者更好的是,是
if (prop.GetCustomAttributes(true).Any(c => c is JsonIgnoreAttribute))
你也可以这样做:
if (prop.GetCustomAttributes(true).OfType<JsonIgnoreAttribute>().Any())
使用
typeof()
有什么问题?或者更好的是,是
if (prop.GetCustomAttributes(true).Any(c => c is JsonIgnoreAttribute))
你也可以这样做:
if (prop.GetCustomAttributes(true).OfType<JsonIgnoreAttribute>().Any())
有一个将所需类型作为参数的:
prop.GetCustomAttributes(typeof(JsonIgnoreAttribute), true)
但是当您实际检查属性的存在时,您应该使用:
这不会实例化属性,因此性能更高
如果不需要inherit参数,可以编写:
if (prop.IsDefined(typeof(JsonIgnoreAttribute)))
由于某些原因,此参数在属性和事件的MemberInfo.IsDefined
函数中被忽略,但在Attribute.IsDefined
中被考虑。算了吧
请注意,可分配给JsonIgnoreAttribute
的任何类型都将由这些函数匹配,因此也将返回派生类型
作为旁注,您可以直接比较
类型
对象,如下所示:c.GetType()==typeof(JsonIgnoreAttribute)
(是完全相同的类型吗?,或者
c是JsonIgnoreAttribute
(类型是可分配的吗?)有一个将所需类型作为参数的:
prop.GetCustomAttributes(typeof(JsonIgnoreAttribute), true)
但是当您实际检查属性的存在时,您应该使用:
这不会实例化属性,因此性能更高
如果不需要inherit参数,可以编写:
if (prop.IsDefined(typeof(JsonIgnoreAttribute)))
由于某些原因,此参数在属性和事件的MemberInfo.IsDefined
函数中被忽略,但在Attribute.IsDefined
中被考虑。算了吧
请注意,可分配给JsonIgnoreAttribute
的任何类型都将由这些函数匹配,因此也将返回派生类型
作为旁注,您可以直接比较
类型
对象,如下所示:c.GetType()==typeof(JsonIgnoreAttribute)
(是完全相同的类型吗?,或者
c是JsonIgnoreAttribute
(类型是否可分配?)