2013-10-23 44 views
1

直接去点,如何获得c#属性的属性?

我怎样才能得到属性的属性,以及该属性的类型或值? 例如像这样的属性:

[ForeignKey(typeof(SomeObject))] 

我想知道或得到它的类型“SomeObject”。我知道我可以得到Properties()等,但属性我没有Ideia。

这是我的疑问,它吓坏了我。在此先感谢帮助!

回答

3

一旦你得到了PropertyInfo您感兴趣的财产,你只需要调用GetCustomAttributes它:

ForeignKey[] keys = (ForeignKey[]) 
    property.GetCustomAttributes(typeof(ForeignKeyAttribute), false); 

另外还有CustomAttributes财产,但这是只在.NET 4.5和Windows存储应用。

+0

还有一个GetCustomAttributesData(): - http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.getcustomattributesdata.aspx –

+0

@RahulTripathi:是的,但仅限于.NET 4它看起来比我给出的代码更麻烦。 –

+0

嗨,@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。这并不令人满意。对不起,这是格式。 –