C#Mono - 物业名称

时间:2011-10-31 19:25:50

标签: c# reflection mono xamarin.ios

使用C#和MonoTouch / Mono

我需要得到这样的属性名称:

public string BalanceOwing
{
    get { return the-name-of-the-property "BalanceOwing" }
}

3 个答案:

答案 0 :(得分:4)

这里最简单的方法就是你所拥有的 - 一个基本的文字"BalanceOwing"

没有infoof运算符。 在框架内使用表达式树(() => BalanceOwing)或堆栈框架(MethodInfo.GetCurrentMethod())分析的一些有趣的方法,但两者都有性能影响。坦率地说,文字更简单,更直接,更快,只要你对其进行单元测试 - 就像可靠一样。

您还可以查看外部工具,例如PostSharp(SharpCrafters),但又一次:这听起来有点过分了。

答案 1 :(得分:2)

您当然可以创建一个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);

正如Marc所提到的那样,存在性能影响(我们没有正式的基准或当前的基准),但是当我们使用INotifyPropertyChanged行为并在我们的模型中创建强类型存在时,这很适合我们的团队/的ViewModels。

答案 2 :(得分:1)

我倾向于避免对属性进行反思,特别是如果您预期会多次执行此操作。

我的一般想法是在属性顶部使用一个属性,然后将结果缓存到某个地方的静态实例中:

[AttributeUsage(AttributeTargets.Property)]
public class FooNameAttribute : Attribute
{
    public string PropertyName { get; private set; }

    public FooNameAttribute(string propertyName)
    {
        PropertyName = propertyName;
    }
}
相关问题