反思 ExpandoObject
我编写了一个漂亮的函数,它将接受 system.object
,反映其属性并将对象序列化为 JSON 字符串。它看起来像这样:
public class JSONSerializer
{
public string Serialize(object obj)
现在,我希望能够执行此操作来序列化动态/ExpandoObject,但因为我的序列化程序使用反射,所以它无法做到这一点。解决方法是什么?
public class Test
{
public dynamic MakeDynamicCat()
{
dynamic newCat = new ExpandoObject();
newCat.Name = "Polly";
newCat.Pedigree = new ExpandoObject();
newCat.Pedigree.Breed = "Whatever";
return newCat;
}
public void SerializeCat()
{
new JSONSerializer().Serialize(MakeDynamicCat());
}
}
I have written a nifty function that will accept a system.object
, reflect on its properties and serialize the object into a JSON string. It looks like this:
public class JSONSerializer
{
public string Serialize(object obj)
Now, I want to be able to do this to serialize a dynamic/ExpandoObject, but because my serializer uses reflection, it isn't able to do it. What's the workaround?
public class Test
{
public dynamic MakeDynamicCat()
{
dynamic newCat = new ExpandoObject();
newCat.Name = "Polly";
newCat.Pedigree = new ExpandoObject();
newCat.Pedigree.Breed = "Whatever";
return newCat;
}
public void SerializeCat()
{
new JSONSerializer().Serialize(MakeDynamicCat());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为,这个问题非常相似:我该怎么办反映动态对象的成员?
至少答案应该对你有帮助。
I think, this question is very similar: How do I reflect over the members of dynamic object?
At least the answers should help you too.