Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 自定义属性的typeof(类)的等效项_C#_Attributes_Custom Attributes - Fatal编程技术网

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
(类型是否可分配?)