访问属性的最佳方式

Yab*_*rgo 7 .net c# reflection attributes annotations

我正在使用一个使用一些属性标记的框架.这将在MVC项目中使用,并且每次我在视图中查看特定记录时都会发生(例如/ Details/5)

我想知道是否有更好/更有效的方法来做这个或一个好的最佳实践示例.

无论如何,我有几个属性,例如:

[Foo("someValueHere")]
String Name {get;set;}

[Bar("SomeOtherValue"]
String Address {get;set;}
Run Code Online (Sandbox Code Playgroud)

寻找这些属性/对其价值采取行动的最有效方式/最佳做法是什么?

我目前正在做这样的事情:

[System.AttributeUsage(AttributeTargets.Property)]
class FooAttribute : Attribute
{

    public string Target { get; set; }

    public FooAttribute(string target)
    {
        Target = target;
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的方法中,我对这些属性采取行动(简化示例!):

public static void DoSomething(object source)
{
    //is it faster if I make this a generic function and get the tpe from T?
    Type sourceType = source.GetType();

    //get all of the properties marked up with a foo attribute
    var fooProperties =  sourceType
      .GetProperties()
      .Where(p => p.GetCustomAttributes(typeof(FooAttribute), true)
      .Any())
      .ToList();

    //go through each fooproperty and try to get the value set
    foreach (var prop in fooProperties)
    {          
        object value = prop.GetValue(source, null);
        // do something with the value
        prop.SetValue(source, my-modified-value, null);
     }
 }
Run Code Online (Sandbox Code Playgroud)

exa*_*ert 2

Attribute.GetCustomAttributePropertyInfo/MemberInfo.GetCustomAttribute是获取属性对象的推荐方法。

虽然,我通常不会用属性来枚举所有属性;您通常想要使用特定的属性,因此您只需GetCustomAttribute直接调用即可。如果您正在查找任何属性的属性,则最好的方法是枚举那些基于 GetCustomAttribute() 来查找属性的属性。