动态设置CollectionDataContract中的ItemName

时间:2014-03-12 08:12:47

标签: c# dictionary datacontractserializer

我有一个实现CollectionDataContract的类,我想将它用于各种字典。每个字典都有自己的ItemName和KeyName,是否可以动态设置ItemName和KeyName值?我不想为每种字典类型创建一个类。

我想避免这种情况:

[CollectionDataContract(ItemName = "Book", KeyName = "Name")]
public class BookDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
    public BookDictionary() : base(){}
}

[CollectionDataContract(ItemName = "Product", KeyName = "ID")]
public class ProductDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
    public ProductDictionary() : base(){}
}

1 个答案:

答案 0 :(得分:-1)

试试这个:

var obj = new ExpandoObject();
DataSet ds = GetObjectProperties() // returns dataset having the properties as key and value pair;
if (ds.Tables["BookTable"].Rows.Count > 0)
{
    foreach (DataRow dr in ds.Tables["BookTable"].Rows)
    {
        string KeyName = dr["KeyName"].ToString();
        string ValueName= dr["ValueName"].ToString();
        obj[KeyName] = ValueName;
    }
}
dynamic DynObj = obj;