动态添加属性的一类 [英] Adding properties dynamically to a class
问题描述
在我的课堂我有私有变量和这类似的房屋
私人字符串_itemCOde =的String.Empty;
私人字符串_itemName =的String.Empty;
公共字符串ItemCode
{
{返回_itemCode; }
集合{_itemCode =值== NULL?值:value.Trim();}
}
公共字符串ITEMNAME
{
{返回_itemName; }
集合{_itemName =值== NULL?值:value.Trim();}
}
根据这一特性创建项目从SQL表中选择数据后的对象。
现在,如果数据库表的改变,并添加了一个名为费用新列,然后我有另一个属性添加到类。无需增加新的属性的类有什么办法根据动态表中的字段都声明属性。
您可以使用一个 ExpandoObject
:
表示一个对象,其成员可以
动态添加和
运行时间删除。
块引用>
动态的expando =新ExpandoObject();
expando.Cost = 42.0;
expando.ItemName =鞋;
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.
解决方案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";
这篇关于动态添加属性的一类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!