2010-09-14 72 views
0

我已經使用動態對象,但這裏是列名來自預定義的字符串數組的情況。如何在運行時使用這些預先創建對象 - 定義的一組列值? 我想這樣做的原因是創建一個自定義類,並在其中添加自定義驗證屬性,以便我可以在運行時使用反射來填充這些動態對象映射到我的自定義類的值,並使用單個驗證值功能。動態對象C#4.0,在運行時從預先定義的值創建列

dynamic x = new MyCustomClass(); 
x.Name = "Jones"; // The Field or Column name "Name" comes from a array of strings. 

Validator.Validate(x); //Here i use reflection to iterate through the custom attributes on MyCustomClass and validate them based on conditions. 

是否可以這樣做x."Name" = "Jones"; :-)

+0

expando對象看起來像他們會做你以後的事情 - 檢查3/4在這個鏈接下:http://msdn.microsoft.com/en-us/magazine/ff796227.aspx – Will 2010-09-14 05:59:43

回答

0

我會建議也許添加一個索引器屬性到你的MyCustomClass?

public string this[string binder] { 
    get { 
     string result; 
     return (this.TryGetMember(binder, out result)) ? result : string.Empty 
    } 
    set { 
     this.TrySetMember(binder, value); 
    } 
} 

x["Name"] = "Jones";