Anonymous class implementing interface [duplicate]
I have the following code inside a method:
var list = new[]
{
new { Name = "Red", IsSelected = true },
new { Name = "Green", IsSelected = false },
new { Name = "Blue", IsSelected = false },
};
I would like to call a function that requires a list of elements with each element implementing an interface (ISelectable). I know how this is done with normal classes, but in this case I am only trying to fill in some demo data.
Is it possible to create an anonymous class implementing an interface?
like this:
new { Name = "Red", IsSelected = true } : ISelectable
No, this is not possible.
An anonymous type is meant to be a lightweight transport object internally. The instant you require more functionality than the little syntax provides, you must implement it as a normal named type.
Things like inheritance and interface implementations, attributes, methods, properties with code, etc. Not possible.
The open source framework impromptu-interface will allow you to effectively do this with a lightweight proxy and the DLR.
new { Name = "Red", IsSelected = true}.ActLike<ISelectable>();
Even if you could do this, you almost certainly would not want to since a method would know everything about the anonymous class (i.e. there is no encapsulation and also no benefit in accessing things indirectly).
On the other hand, I've thought about how such a feature might look (potentially useful if I want to pass an anonymously typed object to a method expecting a particular interface... or so I thought).
The most minimal syntax for an anonymous type that inherits an interface IFoo would be something like
new {IFoo.Bar = 2} // if IFoo.Bar is a property
or
new {IFoo.Bar() = () => do stuff} if IFoo.Bar is a method
But this is the simple case where IFoo only has one property or method. Generally, you would have to implement all of IFoo's members; including read/write properties and events which is currently not even possible on anonymously typed objects.
精彩评论