C# 为什么在使用PropertyDescriptor和PropertyInfo时获取属性的工作方式不同?
我知道调用GetCustomAttribute会返回一个新生成的属性,但为什么不能使用attribute属性获取该属性呢 我附上了这个例子: 定义:C# 为什么在使用PropertyDescriptor和PropertyInfo时获取属性的工作方式不同?,c#,reflection,attributes,propertyinfo,propertydescriptor,C#,Reflection,Attributes,Propertyinfo,Propertydescriptor,我知道调用GetCustomAttribute会返回一个新生成的属性,但为什么不能使用attribute属性获取该属性呢 我附上了这个例子: 定义: public class MyTestAttribute : Attribute { public int Test { get; set; } } public class TestClass { [MyTest] public int Property { ge
public class MyTestAttribute : Attribute
{
public int Test { get; set; }
}
public class TestClass
{
[MyTest]
public int Property { get; set; }
}
代码:
我想你读过@PaulZahra-谢谢你。我不熟悉这些区别。我会在谷歌上搜索一下,看看它们的区别。
// PropertyInfo
var prop = typeof(TestClass).GetProperty("Property");
var attr1 = prop.GetCustomAttribute(typeof(MyTestAttribute), false) as MyTestAttribute;
attr1.Test = 12;
var attr2 = prop.GetCustomAttribute(typeof(MyTestAttribute), false) as MyTestAttribute;
// attr2.Test == 0 since GetCustomAttribute creates a new attribute.
var attr3 = prop.Attributes; //attr3 = None
// PropertyDescriptor
var tProp = TypeDescriptor.GetProperties(typeof(TestClass)).Cast<PropertyDescriptor>().First(p => p.Name == "Property");
var tAttr1 = tProp.Attributes.Cast<Attribute>().OfType<MyTestAttribute>().First();
tAttr1.Test = 12;
var tProp2 = TypeDescriptor.GetProperties(typeof(TestClass)).Cast<PropertyDescriptor>().First(p => p.Name == "Property");
var tAttr2 = tProp2.Attributes.Cast<Attribute>().OfType<MyTestAttribute>().First();
// tAttr2.Test == 12