0

给一个像下面这样的类,我怎样才能找到一个特定属性的名称?

public class Student
{
    public int Grade
    {
        get;
        set;
    }

    public string TheNameOfTheGradeProperty
    {
        get
        {
            return ????
        }
    }

    // More properties..    
}

所以我想从 TheNameOfTheGradeProperty 属性中返回字符串“Grade”。我问的原因是我不想使用硬编码字符串,而是使用 lambda 表达式或其他东西。

我怎样才能做到这一点?

4

3 回答 3

2

可以使用表达式来查找属性的名称,使用简单的扩展方法,您可以在任何对象上使用它......如果您需要将其限制为一组对象,您可以在 T 上应用通用约束。希望这可以帮助

public class Student
{
    public int Grade { get; set;}
    public string Name { get; set; }

    public string GradePropertyName
    {
        get { return this.PropertyName(s => s.Grade); }
    }

    public string NamePropertyName
    {
        get { return this.PropertyName(s => s.Name); }
    }
}

public static class Helper
{
    public static string PropertyName<T, TProperty>(this T instance, Expression<Func<T, TProperty>> expression)
    {
        var property = expression.Body as MemberExpression;

        if (property != null)
        {
            var info = property.Member as PropertyInfo;
            if (info != null)
            {
                return info.Name;
            }
        }

        throw new ArgumentException("Expression is not a property");
    }
}
于 2010-02-16T03:42:25.553 回答
1
using System.Reflection;

return typeof(Student).GetProperty("Grade").Name;

但是正如您所看到的,使用反射(以这种方式)您并没有那么遥遥领先,因为“等级”字符串仍然是硬编码的,这意味着在这种情况下它更有效return "Grade"


我喜欢做的一件事是创建自定义属性并将其添加到这样的成员。以下内容使您不必使用硬编码字符串“Grade”。

public class Student {

// TAG MEMBER WITH CUSTOM ATTRIBUTE
[GradeAttribute()]
public int Grade
{
    get;
    set;
}

public string TheNameOfTheGradeProperty
{
    get
    {
        /* Use Reflection.
           Loop over properties of this class and return the
           name of the one that is tagged with the 
           custom attribute of type GradeAttribute.
        */
    }
}

// More properties..    

} 

可以在此处找到创建自定义属性

于 2010-02-16T03:29:21.003 回答
1

你有一个很奇怪的要求。你是说你不想使用硬编码的字符串,因为你想TheNameOfTheGradeProperty在重构类时保持最新?如果是这样,这是一种奇怪的方法:

public class Student
{
    public int Grade { get; set; }

    public string TheNameOfTheGradeProperty
    {
        get
        {
            Expression<Func<int>> gradeExpr = () => this.Grade;
            MemberExpression body = gradeExpr.Body as MemberExpression;
            return body.Member.Name;
        }
    }
}
于 2010-02-16T03:37:49.107 回答