获取类属性名 [英] Get class property name

查看:187
本文介绍了获取类属性名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我使用的数据绑定WinForm应用程序收集的数据。一切看起来正常,只是,我要链接的属性文本编辑使用字符串:

I have my winform application gathering data using databinding. Everything looks fine except that I have to link the property with the textedit using a string:

Me.TextEdit4.DataBindings.Add(新System.Windows.Forms.Binding(的EditValue,Me.MyClassBindingSource,MyClassProperty,真))

Me.TextEdit4.DataBindings.Add(New System.Windows.Forms.Binding("EditValue", Me.MyClassBindingSource, "MyClassProperty", True))

这工作正常,但如果我改变了类的属性名,编译器显然不会提醒我。

This works fine but if I change the class' property name, the compiler obviously will not warn me .

我希望能够通过反射来获取属性名称,但我不知道如何指定我想要的属性的名称(我只知道如何在类的所有属性之间的循环)

I would like to be able to get the property name by reflection but I don't know how to specify the name of the property I want (I only know how to iterate among all the properties of the class)

你知道吗?

推荐答案

下面是一个例子就是我讲的:

Here is an example of what I'm talking about:

[AttributeUsage(AttributeTargets.Property)]
class TextProperyAttribute: Attribute
{}

class MyTextBox
{
    [TextPropery]
    public string Text { get; set;}
    public int Foo { get; set;}
    public double Bar { get; set;}
}


static string GetTextProperty(Type type)
{
    foreach (PropertyInfo info in type.GetProperties())
    {
        if (info.GetCustomAttributes(typeof(TextProperyAttribute), true).Length > 0)
        {
            return info.Name;
        }
    }

    return null;
}

...

Type type = typeof (MyTextBox);

string name = GetTextProperty(type);

Console.WriteLine(name); // Prints "Text"

这篇关于获取类属性名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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