2010-12-21 37 views
2

的对象我有类方法:如何延长匿名类

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有新的属性。请帮助。

+0

,你为什么和匿名类这样做呢? – jason 2010-12-21 20:00:34

+0

我正在使用ASP.NET MVC,我希望任何JSON数据都可以用我的调试信息进行扩展。 – 2010-12-21 20:05:36

回答

9

你不能那样做。

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

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

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

+0

谢谢,我会试试看。 – 2010-12-21 20:10:10

1

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

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