2010-09-14 26 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";