1
直接去点,如何获得c#属性的属性?
我怎样才能得到属性的属性,以及该属性的类型或值? 例如像这样的属性:
[ForeignKey(typeof(SomeObject))]
我想知道或得到它的类型“SomeObject”。我知道我可以得到Properties()等,但属性我没有Ideia。
这是我的疑问,它吓坏了我。在此先感谢帮助!
直接去点,如何获得c#属性的属性?
我怎样才能得到属性的属性,以及该属性的类型或值? 例如像这样的属性:
[ForeignKey(typeof(SomeObject))]
我想知道或得到它的类型“SomeObject”。我知道我可以得到Properties()等,但属性我没有Ideia。
这是我的疑问,它吓坏了我。在此先感谢帮助!
一旦你得到了PropertyInfo
您感兴趣的财产,你只需要调用GetCustomAttributes
它:
ForeignKey[] keys = (ForeignKey[])
property.GetCustomAttributes(typeof(ForeignKeyAttribute), false);
另外还有CustomAttributes
财产,但这是只在.NET 4.5和Windows存储应用。
还有一个GetCustomAttributesData(): - http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.getcustomattributesdata.aspx –
@RahulTripathi:是的,但仅限于.NET 4它看起来比我给出的代码更麻烦。 –
嗨,@JonSkeet!我写的东西是这样的:的foreach(在性能VAR属性) \t \t \t { \t \t \t \t Console.WriteLine(property.Name); \t \t \t \t的foreach(ForeignKeyAttribute FOREIGNKEY在 \t \t \t \t property.GetCustomAttributes(typeof运算(ForeignKeyAttribute),假)) \t \t \t \t { \t \t \t \t \t Console.WriteLine(FOREIGNKEY); \t \t \t \t}在提示符下输出:Namespace.Example.Model.ForeignKeyAttribute。这并不令人满意。对不起,这是格式。 –