2011-01-14 144 views
4

我是googling試圖找到一種方法來呼叫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

順便說一句,我只是測試,以我的財產重新命名OneTwo和Visual Studio打開new { this.One }new { One = this.Two },其與GetName使用時函數給了我"One",這使得整個事物無用,因爲我將傳遞給Control.DataBindings.Add的名稱在重命名屬性後仍然是「一」。

+0

我不能相信VS被髮射`新{this.One}`,除非你在第一個PL使用匿名類高手。 – leppie 2011-01-14 08:53:35

+0

另請參閱http://stackoverflow.com/questions/1329138/how-to-make-databinding-type-safe-and-support-refactoring – 2011-01-14 11:42:00

回答

6

new { this.One }使用一個屬性創建anonymous type的實例,因爲您沒有指定名爲「One」的名稱。這就是它工作的原因。

如果您使用new { One = this.Two },那麼您將該屬性命名爲「One」。如果你忽略了「One =」這個部分,它會再次起作用。

但是,如果您不知道如何使用它,並且不使用匿名類型調用它,那麼您使用的方法可能會被誤解。

還有,如果你不希望使用字符串文字的另一種方式,就是在這裏,你可以在網上找到一個例子:
http://www.codeproject.com/Tips/57234/Getting-Property-Name-using-LINQ.aspx

3

不,你不必堅持字符串文字:

public static class ControlBindingsCollectionExtensions 
{ 
    public static void Add<T>(this ControlBindingsCollection instance, Expression<Func<T, object>> property) 
    { 
     var body = property.Body as UnaryExpression; 
     var member = body.Operand as MemberExpression; 
     var name = member.Member.Name; 
     instance.Add(name); 
    } 
} 

用法:

Control.DataBindings.Add<MyClass>(m => m.MyProperty);