Dynamic Object C# 4.0 , Creating columns at runtime from Pre-defined values
I have used dynamic object but here is a situation where the column names comes from a pre-defined string arrays.How can i create objects at runtime with these pre-defined set of column values?. The reason why i wanted to do this way is to create a custom cl开发者_如何转开发ass and add custom validation attributes in it so that i can use reflection at runtime to populate values to these dynamic objects mapped to my custom class and validate the values using a single function.
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.
Is it possible to do something like this x."Name" = "Jones"
; :-)
I would suggest perhaps adding an indexer property to your 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";
精彩评论