Is there a concise way to decorate an anonymous type?
Suppose we have an instance of an anonymous type:
var b = new {
Length = 5
, Width = 6
// 40 more properties
};
and we want to create an instance of a different anonymous type, which has all the same members as the first type, with the same values as the first instance, but with one additional member:
var d = new {
b.Length
, b.Width
// the same 40 more properties, with values from b
, Jiffle = "custard"
};
It's nice that the compiler will automagically work out what we want to call the members of d
's type, just from this initializer. But is there any way we can avoid have to explicitly refer to all 42 members that we want to copy ove开发者_JAVA技巧r?
This sounds like you need well defined types with an inheritance pattern.
What your saying above is that d is an extension of b or:
class b
{
Length = 5
, Width = 6
// 40 more properties
}
class d : b
{
Jiffle = "custard"
}
Composition?
var d = new { B = b, Jiffle = "custard" }
d.B.Length;
Pulling dlev's comment out into an answer so I can accept it:
I don't think there is a simple way, and it certainly seems like an abuse of anonymous types. If you need that many fields and that much commonality between types, just declare the types yourself. If you're looking to add these fields dynamically, ExpandoObject could help.
精彩评论