1

我有以下定义:

public class cell : DynamicObject {

}

[DataContract]
public class rows {
  [DataMember]
   public List<cell> rows;
}

稍后在我做的代码中:

dynamic dtCell = new cell();

我需要能够每次都创建具有不同名称的属性。所以我能够得到像这样的json:

{ color: 'red', category: 'car'} or { country: 'US', city: 'Tampa', county: '...', ... }

如何为动态对象创建属性,就像在 javascript 中向字典添加属性或类似的东西一样。

我试过了:dtCell.GetType().GetProperty('city')正如我在几篇文章中发现的那样,对象返回是null.

当我做:

dtCell.GetType().GetProperty('city').SetValue(dtCell, 'Tampa', null)

我得到了例外:dtCell.GetType().GetProperty("CustomerId").SetValue(dtCell, 3, null)' threw an exception of type 'System.Reflection.TargetInvocationException' dynamic {System.Reflection.TargetInvocationException}

帮助表示赞赏!

4

1 回答 1

2

您可以使用 Dictionary 代替 DynamicObject。例如,

Dictionary<string, string> dict = new Dictionary<string, string>()
{
    {"country","US"},  {"city","Tampa"},  {"county","..."}
};

var json = new JavaScriptSerializer().Serialize(dict);

会给{"country":"US","city":"Tampa","county":"..."}

也可以使用匿名类

var obj = new { color = "red", category = "car" };
var json2 = new JavaScriptSerializer().Serialize(obj);
于 2013-05-28T22:17:03.373 回答