Adding members to a dynamic object at runtime

前端 未结 5 1116
无人共我
无人共我 2020-12-24 11:53

I am exploring the DynamicObject model in .NET 4.0. The application is one where an object will be described through some sort of text/xml file, and the program must create

5条回答
  •  星月不相逢
    2020-12-24 12:19

    I'm not sure you want to use a dynamic object in this case.

    dynamic in c# lets you do things like :

      dynamic something = GetUnknownObject();
      something.aPropertyThatShouldBeThere = true;
    

    If you use an ExpandoObject, you can:

      var exp = GetMyExpandoObject();
      exp.APropertyThatDidntExist = "something";
    

    Both of these let you use the propertyname as if it actually exists at compile time. In your case, you won't need to use this syntax at all, so I'm not sure that it would give you any benefit whatsoever. Instead, why not just use a Dictionary, and:

    var props = new Dictionary();
       foreach( var someDefinintion in aFile)
       {
          props[ someDefinition.Name] = someDefinition.value;
       }
    

    Because a Dictionary is basically what an expando object is - but it has support for a different syntax. Yes, I'm simplifying - but if you're not using this from other code or through binding / etc, then this is basically true.

提交回复
热议问题