动态对象C#4.0,在运行时从预定义值创建列

时间:2010-09-14 05:44:30

标签: 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"; : - )

1 个答案:

答案 0 :(得分: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";
相关问题