コンパイル時にプロパティの名前を知っていますか? これを行うことができるため:
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);
これは、同じアセンブリ内の 2 つの匿名型が、同じ順序で同じ型の同じ名前を持つプロパティを持つ、同じ型であるという事実に大きく依存していることに注意してください。
しかし、これを行う場合は、具体的な型を作成してみませんか?
出力:
True