Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

c# - Adding properties dynamically to a class

In my class I have private variables and properties like this.

private string _itemCOde=string.Empty;
private string  _itemName=string.Empty;

public string ItemCode
{
    get { return _itemCode; }
    set { _itemCode = value == null ? value : value.Trim();}
}

public string ItemName
{
    get { return _itemName; }
    set { _itemName = value == null ? value : value.Trim();}
}

According to this properties I create Item objects after selecting the data from the sql table.

Now, if database table altered and add a new column called cost, then I have to add another property to the class. Without adding new properties to the class is there any way do declare properties according to the table fields dynamically.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use an ExpandoObject:

Represents an object whose members can be dynamically added and removed at run time.

dynamic expando = new ExpandoObject();
expando.Cost= 42.0;
expando.ItemName = "Shoes";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...