2011-02-03 141 views
10

我寫了一個自定義屬性,我使用一類的某些成員:從自定義屬性裝飾屬性獲取價值?

public class Dummy 
{ 
    [MyAttribute] 
    public string Foo { get; set; } 

    [MyAttribute] 
    public int Bar { get; set; } 
} 

我能夠得到的類型的自定義屬性,找到我的具體屬性。我無法弄清楚如何做的是獲取分配屬性的值。當我拿一個Dummy的實例並將它作爲一個對象傳遞給我的方法時,我如何從Property.GetProperties()獲取PropertyInfo對象並獲取賦給.Foo和.Bar的值?

編輯:

我的問題是,我無法弄清楚如何正確地調用的GetValue。

void TestMethod (object o) 
{ 
    Type t = o.GetType(); 

    var props = t.GetProperties(); 
    foreach (var prop in props) 
    { 
     var propattr = prop.GetCustomAttributes(false); 

     object attr = (from row in propattr where row.GetType() == typeof(MyAttribute) select row).First(); 
     if (attr == null) 
      continue; 

     MyAttribute myattr = (MyAttribute)attr; 

     var value = prop.GetValue(prop, null); 
    } 
} 

然而,當我這樣做時,prop.GetValue電話給了我TargetException - 對象不匹配目標類型。我如何構造這個調用來獲得這個值?

回答

11

你需要傳遞對象本身的GetValue,而不是一個屬性對象:

var value = prop.GetValue(o, null); 

還有一件事 - 你不應該使用.First(),而是.FirstOrDefault(),因爲你的代碼會拋出一個exc如果某些屬性不包含任何屬性:

object attr = (from row in propattr 
       where row.GetType() == typeof(MyAttribute) 
       select row) 
       .FirstOrDefault(); 
3

您使用.GetProperties()得到PropertyInfo陣列,並呼籲各

呼叫PropertyInfo.GetValue方法是這樣:

var value = prop.GetValue(o, null); 
+0

澄清; OP將需要一個Dummy類的實例,以便從中獲取屬性值。類型本身是不夠的。 – KeithS 2011-02-04 00:36:11

+0

我已經更新了我的問題 - 我的問題與.GetValue完全相同,以及如何調用它以便實際工作。 – Joe 2011-02-04 01:23:28