11 .net reflection
我有我的winform应用程序使用数据绑定收集数据.一切都很好,除了我必须使用字符串链接属性与textedit:
Me.TextEdit4.DataBindings.Add(New System.Windows.Forms.Binding("EditValue",Me.MyClassBindingSource,"MyClassProperty",True))
这工作正常,但如果我更改类的属性名称,编译器显然不会警告我.
我希望能够通过反射获取属性名称,但我不知道如何指定我想要的属性的名称(我只知道如何在类的所有属性之间进行迭代)
任何的想法?
如果您使用的是C#3.0,则可以动态获取属性的名称,而无需对其进行硬编码.
private string GetPropertyName<TValue>(Expression<Func<BindingSourceType, TValue>> propertySelector)
{
var memberExpression = propertySelector.Body as MemberExpression;
return memberExpression != null
? memberExpression.Member.Name
: string.empty;
}
Run Code Online (Sandbox Code Playgroud)
BindingSourceType数据源对象实例的类名在哪里.
然后,您可以使用lambda表达式以强类型方式选择要绑定的属性:
this.textBox.DataBindings.Add(GetPropertyName(o => o.MyClassProperty),
this.myDataSourceObject,
"Text");
Run Code Online (Sandbox Code Playgroud)
它将允许您安全地重构代码,而无需制动所有数据绑定内容.但就性能而言,使用表达式树与使用反射相同.
之前的代码非常丑陋且未经检查,但您明白了.
这是我正在谈论的一个例子:
[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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7235 次 |
| 最近记录: |