我在谷歌上搜索,试图找到一种调用Control.DataBindings.Add
的方法,而不使用字符串字面值,而是从属性本身获取属性名称,我认为这样会更少出错,至少对于我的特定情况是这样的,因为当我重命名一个属性时,我通常让Visual Studio来完成。所以我的代码应该是这样的:DataBindings.Add(GetName(myInstance.myObject)...
而不是DataBindings.Add("myObject"...
。所以我找到了这个:
static string GetName<T>(T item) where T : class
{
var properties = typeof(T).GetProperties();
if (properties.Length != 1) throw new Exception("Length must be 1");
return properties[0].Name;
}
假设我有一个名为
One
的属性,那么可以这样调用:string name = GetName(new { this.One });
,这将返回"One"
。我不知道它为什么能运行,是否安全。我甚至不知道new { this.One }
是什么意思。而且我也不知道在哪种情况下properties.Length
不为1。顺便说一下,我刚测试了一下把
One
属性重命名为Two
,Visual Studio就把new { this.One }
变成了new { One = this.Two }
,当与GetName
函数一起使用时,它给我返回了"One"
,这使得整个过程变得没有意义,因为无论如何我都会传递给Control.DataBindings.Add
一个名为"One"的属性名称。
new { this.One }
,除非你一开始就使用了匿名类。 - leppie