你知道在编译时的属性的名称?因为你可以这样做:
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
,你为什么和匿名类这样做呢? – jason 2010-12-21 20:00:34
我正在使用ASP.NET MVC,我希望任何JSON数据都可以用我的调试信息进行扩展。 – 2010-12-21 20:05:36