您在编译时知道属性的名称吗?因为你可以这样做:
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