문제

This question already has an answer here:

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top