开发者

Adding late-bound information to an object in C#, using dynamic keyword?

开发者 https://www.devze.com 2023-01-14 06:51 出处:网络
I have an object, and before I serialize it to Json, I\'d like to add a property to it. So my object will look like this:

I have an object, and before I serialize it to Json, I'd like to add a property to it. So my object will look like this:

    public class MySpecialObject {
       public int Id { get; set; }
       public string OneProperty { get; set; }
       public string ASecondProperty { get; set; }
    }

However, much later in the program I often want to add a property or two. This usually occurs in my controller, right before converting it to Json. I'd like to do something like this:

    ///Retrieve object from database
    var MySpecialObject = specialObjectRepository.Get(id);

    MySpecialObject.["DynamicProperty"] = "Dynamic Property!";

    ///Pretend I do Json serialization here
    return MySpecialObject;

That's obviously made up, but I hope what I'm trying to do is clear. In Javascript this is really easy to do since it is loosely typed. I thought with the dynamic keyword in C# 4.0 this would be possible, but it looks like that's not what it is for (though I could be completely missing the obvious). I guess I could create a class for these kinds of situations开发者_开发技巧, but it'd be easier to just do it in one line. I know this sounds lazy, but it feels like what I'm trying to do should be possible.


You want to inherit from ExpandoObject. It implements all the necessary plumping for a dynamic object.


You have to use the new ExpandoObject class:

    public class MySpecialObject:ExpandoObject {
       public int Id { get; set; }
       public string OneProperty { get; set; }
       public string ASecondProperty { get; set; }
    }

and, before serialization,simply write:

var MySpecialObject = specialObjectRepository.Get(id);

MySpecialObject.DynamicProperty = "Dynamic Property!";

You are not limited to add new properties, you can also add new methods and new events.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号