簡體   English   中英

訪問屬性的最佳方式

[英]Best way to access attributes

我正在使用一個使用一些屬性標記的框架。 這將在MVC項目中使用,並且每次我在視圖中查看特定記錄時都會發生(例如/ Details / 5)

我想知道是否有更好/更有效的方法來做這個或一個好的最佳實踐示例。

無論如何,我有幾個屬性,例如:

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

[Bar("SomeOtherValue"]
String Address {get;set;}

尋找這些屬性/對其價值采取行動的最有效方式/最佳做法是什么?

我目前正在做這樣的事情:

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

    public string Target { get; set; }

    public FooAttribute(string target)
    {
        Target = target;
    }
}

在我的方法中,我對這些屬性采取行動(簡化示例!):

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);
     }
 }

Attribute.GetCustomAttributePropertyInfo / MemberInfo.GetCustomAttribute是獲取屬性對象的推薦方法。

雖然,我通常不會枚舉具有屬性的所有屬性; 您通常希望使用特定屬性,因此您只需直接調用GetCustomAttribute 如果您正在尋找任何屬性的屬性,那么根據GetCustomAttribute()的方式枚舉那些尋找屬性的屬性,就是最好的方法。

在處理屬性時沒有太多選擇 - 你的代碼是正確的,也是合理的,作為你的主要性能問題也是不可能的。 唯一的直接問題是將ToList調用作為絕對不必要的。


附注:與績效相關的問題應該近似

“我測量了我的代碼,部分XXX似乎占用了太多時間(YYY)。這段代碼的時間目標是ZZZ。我的做法是合理的/我可以在哪里改進它?”。

請注意,在您的情況下,您缺少YYY和ZZZ時間部分 - 因此您無法確定它是否適合您的情況。 並且您可能希望使用DB /其他IO綁定操作開始測量,因為它更有可能加速您的整體代碼。

在您認為此屬性相關代碼是主要性能問題之后,您可以考慮某種結果緩存甚至某種類型的代碼生成(通過緩存lambdas來設置必要的值甚至完整的IL生成)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM