【发布时间】:2013-05-24 00:42:54
【问题描述】:
我有以下定义:
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}
不胜感激!!!
【问题讨论】:
-
获得
PropertyInfo后,您必须获取GetSetMethodmsdn.microsoft.com/en-us/library/2ef4d5h3.aspx 并针对它运行调用。基本上你调用了错误的方法。
标签: c# wcf c#-4.0 dynamic reflection