【问题标题】:How to extend an object of the anonymous class如何扩展匿名类的对象
【发布时间】:2010-12-21 19:58:01
【问题描述】:

我有类方法:

public object MyMethod(object obj)
{
   // I want to add some new properties example "AddedProperty = true"
   // What must be here?
   // ...

   return extendedObject;
}

还有:

var extendedObject = this.MyMethod( new {
   FirstProperty = "abcd",
   SecondProperty = 100 
});

现在extendedObject 有了新的属性。请帮忙。

【问题讨论】:

  • 你为什么要使用匿名类?
  • 我正在使用 ASP.NET MVC,我希望使用我的调试信息扩展任何 JSON 数据。

标签: c# anonymous-class


【解决方案1】:

你不能那样做。

如果您想要一个可以在运行时添加成员的动态类型,那么您可以使用ExpandoObject

表示一个对象,其成员可以在运行时动态添加和删除。

这需要 .NET 4.0 或更高版本。

【讨论】:

    【解决方案2】:

    您可以使用 Dictionary (property, value),或者如果您使用的是 c# 4.0,您可以使用新的动态对象 (ExpandoObject)。

    http://msdn.microsoft.com/en-us/library/dd264736.aspx

    【讨论】:

      【解决方案3】:

      您在编译时知道属性的名称吗?因为你可以这样做:

      public static T CastByExample<T>(object o, T example) {
          return (T)o;
      }
      
      public static object MyMethod(object obj) {
          var example = new { FirstProperty = "abcd", SecondProperty = 100 };
          var casted = CastByExample(obj, example);
      
          return new {
              FirstProperty = casted.FirstProperty,
              SecondProperty = casted.SecondProperty,
              AddedProperty = true
          };
      }
      

      然后:

      var extendedObject = MyMethod(
          new {
              FirstProperty = "abcd",
              SecondProperty = 100
          }
      );
      
      var casted = CastByExample(
          extendedObject,
          new {
              FirstProperty = "abcd",
              SecondProperty = 100,
              AddedProperty = true 
          }
      );
      Console.WriteLine(xyz.AddedProperty);
      

      请注意,这在很大程度上依赖于这样一个事实,即同一程序集中的两个匿名类型具有相同名称的相同类型的相同顺序的相同类型的属性。

      但是,如果您要这样做,为什么不直接创建具体类型呢?

      输出:

      True
      

      【讨论】:

      • 谢谢,但我不知道属性的名称。属性可以是任意的。
      猜你喜欢
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 2016-08-02
      • 2017-08-15
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多