English 中文(简体)
在C# 3.5中,从类内部查找类的特定属性名称
原标题:Finding the name of a particular property of a class from within the class in C# 3.5

像下面这样给一个类,我该如何找到一个特定属性的名称? (Xiàng xiàmiàn zhèyàng gěi yígè lèi, wǒ gāi rúhé zhǎodào yígè tèdìng shǔxìng de míngchēng?)

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

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

    // More properties..    
}

因此,我要从“NameOftheGradeProperty”财产中归还“Grade”。 要求这样做的理由是,我不想使用硬编码拼法,而是要用斜体表示或其它东西。

我该如何实现这个目标?

问题回答

可以使用一个表达式来查找属性的名称,使用一个简单的扩展方法,您可以将其用于任何对象... 如果您需要将其限制为一组对象,可以在 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");
    }
}

你有一个非常奇怪的请求。你是否想要不使用硬编码的字符串,因为如果你重构了类,你希望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;
        }
    }
}
using System.Reflection;

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

但正如您所看到的那样,使用反射(以这种方式)并没有让您领先很远,因为“Grade”字符串仍然是硬编码的,这意味着在这种情况下, 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..    

} 

在此处可以找到创建自定义属性的方式。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签