获取属性的属性知道它是什么

时间:2013-07-19 10:49:21

标签: c# attributes

想要做一些非常简单的事情,那就是获取属性的属性。现在我知道如何通过PropertyInfo等做到这一点,但我知道我想获得属性的属性是这样可以做类似的事情:

MyAttribute attr = (MyAttribute)customer.Forename;

理想情况下要避免反思。我能想到的唯一方法是做一个linq语句,如:

PropertyInfo pi = typeof(Customer).GetProperties().Where(x => x.Name == "Forename").FirstOrDefault();
MyAttribute attri = (MyAttribute)Attribute.GetCustomAttribute(pi, typeof(MyAttribute));

不喜欢这样,因为我必须对属性名称进行字符串比较:(

考虑到我知道属性我想获得属性我认为可能有一种更简单的方法吗?

1 个答案:

答案 0 :(得分:0)

Kzu写了一段代码以允许强烈反映。

在此处查看博文:http://blogs.clariusconsulting.net/kzu/linq-beyond-queries-strong-typed-reflection/

您现在可以将其作为NuGet包(NETFx Reflector)获取:

http://nuget.org/packages/netfx-Reflector

// Void static method
MethodInfo cw = Reflect.GetMethod(() => Console.WriteLine);

// Instance void method
MethodInfo mi = Reflect<IView>.GetMethod(v => v.Show);

// Boolean returning instance method
MethodInfo pi = Reflect<IViewModel>.GetMethod<bool>(v => v.Save);