您可以澄清一下你的問題。這對我來說太模糊了。
你是在找這個嗎?
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
時,您的代碼將在運行時中斷,因爲您可能很容易忘記重寫該函數的字符串參數。使用其他版本,至少編譯器會爲您提供錯誤。
如果您提供更多信息,我可以編寫更具體的答案。
未知的問題:你爲什麼?如果你想定義許多這樣的屬性,那就是代碼生成的用途。 T4包含在VS. – Jon
如果您使用的是.NET 4.5,您可能需要查看「CallerMemberName」屬性:http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute.aspx –
@KooKiz很漂亮。這對於日誌記錄來說非常方便。 – Khan