简体   繁体   English

使用动态关键字将后期绑定信息添加到C#中的对象?

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

I have an object, and before I serialize it to Json, I'd like to add a property to it. 我有一个对象,在将其序列化为Json之前,我想为其添加一个属性。 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. 这通常发生在我的控制器中,就在将其转换为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. 在Javascript中,这是很容易做到的,因为它是松散键入的。 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). 我以为在C#4.0中使用dynamic关键字是可行的,但看起来这不是它的目的(尽管我可能会完全忽略明显的东西)。 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 . 您想从ExpandoObject继承。 It implements all the necessary plumping for a dynamic object. 它为动态对象实现了所有必要的填充。

You have to use the new ExpandoObject class: 您必须使用新的ExpandoObject类:

    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. 您不仅限于添加新属性,还可以添加新方法和新事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM