我如何在C#中的属性来获取一个属性的名称(2.0) [英] How do I get the name of a property from a property in C# (2.0)

查看:132
本文介绍了我如何在C#中的属性来获取一个属性的名称(2.0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以有一个属性,但是这更多的工作比我想去......并没有足够一般。

I know I could have an attribute but that's more work than I want to go to... and not general enough.

我想要做这样的事情。

class Whotsit
{
    private string testProp = "thingy";

    public string TestProp 
    {
        get { return testProp; }
        set { testProp = value; }
    }

}

...

Whotsit whotsit = new Whotsit();
string value = GetName(whotsit.TestProp); //precise syntax up for grabs..

在这里,我期望的值等于TestProp

where I'd expect value to equal "TestProp"

但我不能为我的生活找到合适的反射方法写的GetName方法...

but I can't for the life of me find the right reflection methods to write the GetName method...

编辑:为什么我要这么做?我有一个类来存储设置从名称,值表中读取。这是基于反射的通用方法填充。我很喜欢写反...

Why do I want to do this? I have a class to store settings read from a 'name', 'value' table. This is populated by a generalised method based upon reflection. I'd quite like to write the reverse...

/// <summary>
/// Populates an object from a datatable where the rows have columns called NameField and ValueField. 
/// If the property with the 'name' exists, and is not read-only, it is populated from the 
/// valueField. Any other columns in the dataTable are ignored. If there is no property called
/// nameField it is ignored. Any properties of the object not found in the data table retain their
/// original values.
/// </summary>
/// <typeparam name="T">Type of the object to be populated.</typeparam>
/// <param name="toBePopulated">The object to be populated</param>
/// <param name="dataTable">'name, 'value' Data table to populate the object from.</param>
/// <param name="nameField">Field name of the 'name' field'.</param>
/// <param name="valueField">Field name of the 'value' field.</param>
/// <param name="options">Setting to control conversions - e.g. nulls as empty strings.</param>

public static void PopulateFromNameValueDataTable<T>
        (T toBePopulated, System.Data.DataTable dataTable, string nameField, string valueField, PopulateOptions options)
    {
        Type type = typeof(T);
        bool nullStringsAsEmptyString = options == PopulateOptions.NullStringsAsEmptyString;

        foreach (DataRow dataRow in dataTable.Rows)
        {
            string name = dataRow[nameField].ToString();
            System.Reflection.PropertyInfo property = type.GetProperty(name);
            object value = dataRow[valueField];

            if (property != null)
            {
                Type propertyType = property.PropertyType;
                if (nullStringsAsEmptyString && (propertyType == typeof(String)))
                {
                    value = TypeHelper.EmptyStringIfNull(value);
                }
                else
                {
                    value = TypeHelper.DefaultIfNull(value, propertyType);
                }

                property.SetValue(toBePopulated, System.Convert.ChangeType(value, propertyType), null);
            }
        }
    }

进一步编辑:我只是在code,有Whotsit的实例,我想要得到的TestProp'属性的文本字符串。这似乎有点奇怪,我知道,我可以只使用文字TestProp - 或在我的课到的数据表功能的情况下,我会在PropertyInfos的foreach循环。我只是好奇...

FURTHER I am just in code, have an instance of Whotsit and I want to get the text string of the 'TestProp' property. It seems kind of weird I know, I can just use the literal "TestProp" - or in the case of my class to datatable function I'd be in a foreach loop of PropertyInfos. I was just curious...

原来的code的字符串常量,我发现笨拙。

The original code had string constants, which I found clumsy.

推荐答案

没有,没有什么可以做到这一点。这位前pression whotsit.TestProp 将评估的财产。你想要的是传说中的infoof操作符:

No, there's nothing to do this. The expression whotsit.TestProp will evaluate the property. What you want is the mythical "infoof" operator:

// I wish...
MemberInfo member = infoof(whotsit.TestProp);

正因为如此,你只能使用反射来获取由名称的属性 - 从code没有。 (或者获得所有属性,当然,它仍然无法帮助你和你的样品虽然。)

As it is, you can only use reflection to get the property by name - not from code. (Or get all the properties, of course. It still doesn't help you with your sample though.)

一个替代方案是使用前pression树:

One alternative is to use an expression tree:

Expression<Func<string>> = () => whotsit.TestProp;

然后检查前pression树获取属性。

then examine the expression tree to get the property.

如果没有这种帮助,也许你可以详细了解你为什么要这个功能告诉我们什么?

If none of this helps, perhaps you could tell us more about why you want this functionality?

这篇关于我如何在C#中的属性来获取一个属性的名称(2.0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆