2013-10-09 98 views
1

下面是我目前的狀況....屬性內的反射?

public string Zip { get { return this.GetValue<string>("Zip"); } set { this.SetValue("Zip", value); } } 

我想使這個使用反射動態。 如同,將屬性的類型和名稱傳遞給方法。我不知道該怎麼做,或者甚至有可能。謝謝你的幫助。

編輯:感謝KooKiz我已經能夠更進一步,但仍然不是100%。

public string Zip { get { return this.GetValue<string>(); } set { this.SetValue(value); } } 
+0

未知的問題:你爲什麼?如果你想定義許多這樣的屬性,那就是代碼生成的用途。 T4包含在VS. – Jon

+2

如果您使用的是.NET 4.5,您可能需要查看「CallerMemberName」屬性:http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute.aspx –

+0

@KooKiz很漂亮。這對於日誌記錄來說非常方便。 – Khan

回答

1

您可以澄清一下你的問題。這對我來說太模糊了。

你是在找這個嗎?

public object DoSomething(Type type, string propertyName) 
{ 
    var somethingWithProperty = Activator.CreateInstance(type, null); 
    foreach (PropertyInfo property in somethingWithProperty.GetType().GetProperties()) 
    { 
     if (property.Name == propertyName) 
     { 
      return property.GetValue(somethingWithProperty, null); 
     } 
    } 

    throw new ArgumentException(string.Format("No property was found was found with this on [{0}] with propertyname [{1}]", type, propertyName)); 
} 

或那樣嗎?

public object DoSomething(Func<object> propertyStuff) 
    { 
     return propertyStuff(); 
    } 

用法:

public void FinallyIDoSomethingWithThatSomething() 
{ 
    // first version 
    DoSomething(typeof(StrangeOtherClass), "MyLittleProperty"); 

    // second version 
    DoSomething(() => new StrangeOtherClass().MyLittleProperty); 
    DoSomething(() => MyPropertyInMyOwnClass); 
} 

由於代碼prettifier顯示錯誤顏色的屬性,我會爲他們提供:

public string MyPropertyInMyOwnClass { get { return "Yay or nay."; } } 

請注意,第二個版本更多重構友好第一版當您重構StrangeOtherClass並且您重命名爲MyLittleProperty時,您的代碼將在運行時中斷,因爲您可能很容易忘記重寫該函數的字符串參數。使用其他版本,至少編譯器會爲您提供錯誤。

如果您提供更多信息,我可以編寫更具體的答案。