使用C#和MonoTouch的/單聲道C#單 - 屬性名
我需要這樣的屬性的名稱:
public string BalanceOwing
{
get { return the-name-of-the-property "BalanceOwing" }
}
使用C#和MonoTouch的/單聲道C#單 - 屬性名
我需要這樣的屬性的名稱:
public string BalanceOwing
{
get { return the-name-of-the-property "BalanceOwing" }
}
您當然可以創建一個reusable method這將爲您提供您所需要的。
protected String GetPropertyName<TProperty>(Expression<Func<TProperty>> propertyExpresion)
{
var property = propertyExpresion.Body as MemberExpression;
if (property == null || !(property.Member is PropertyInfo) ||
!IsPropertyOfThis(property))
{
throw new ArgumentException(string.Format(
CultureInfo.CurrentCulture,
"Expression must be of the form 'this.PropertyName'. Invalid expression '{0}'.",
propertyExpresion), "propertyExpression");
}
return property.Member.Name;
}
要使用你會通過在屬性的名稱...
String propertyName = GetPropertyName(() => this.BalanceOwing);
正如馬克提到的,有性能問題(然而什麼,我們已正式基準或作爲當前說明)這使我們的團隊在使用INotifyPropertyChanged
行爲並在我們的Models/ViewModels中創建一個強類型存在時非常合適。
這裏最簡單的方法是正是你有什麼 - 一個基本的文字"BalanceOwing"
。
運營商沒有infoof
。有是一些有趣的方法來做到這一點在框架內或表達式樹(() => BalanceOwing
)或分析棧幀(MethodInfo.GetCurrentMethod()
),但都有性能影響。坦率地說,文字更簡單,更直接,更快,並且只要你單元測試 - 就像可靠。
您還可以查看外部工具,例如PostSharp(SharpCrafters),但是同樣如此:這聽起來有點矯枉過正。
我傾向於避免對屬性進行反思,特別是如果您曾經預測過不止一次。
我的總體思路是對財產的頂部使用的屬性,然後將結果緩存到一個靜態實例的地方:
[AttributeUsage(AttributeTargets.Property)]
public class FooNameAttribute : Attribute
{
public string PropertyName { get; private set; }
public FooNameAttribute(string propertyName)
{
PropertyName = propertyName;
}
}
什麼?我們需要更多的背景知識。什麼是這個名稱應該是什麼意思?你是否說你想用反射來獲得名稱的屬性值?什麼對象?等等。 –
你究竟在哪裏遇到困難?目前還不清楚你在這裏試圖達到什麼目的。 – Oded
即,您想要獲取當前代碼正在執行的屬性的名稱。對?!?我確實認爲這隻適用於像[PostSharp](http://www.sharpcrafters.com/)這樣的Aspect Orientiated Programming(AOP)工具。 –