如何在C#中创建带接口的匿名类


how to create anonymous class with interface in C#

本问题已经有最佳答案,请猛点这里访问。

大家都知道,C 3.5中有一个新概念,即匿名类型。如何创建实现一个接口的匿名类型。实际上,在为组件编写UT的同时,为了提高行覆盖率,我需要这样做。

请帮我一下。


C不支持创建实现接口的匿名类型。来自msdn:

Anonymous types are class types that
consist of one or more public
read-only properties. No other kinds
of class members such as methods or
events are allowed. An anonymous type
cannot be cast to any interface or
type except for object.

号

您可能应该定义一个新的具体类型,而不是使用匿名类型,这样您就可以实现所需的接口。


听起来你在寻找一个类似moq的模拟框架:http://code.google.com/p/moq/

它没有利用Anonymous Types -这是非常不同的Java版本


不可能让annonymous类型实现接口。由于annonymous类型是只包含数据的,所以看起来您希望实现一个只包含数据的接口。我确实认为这是一个糟糕的设计。您应该创建一个DTO(数据传输对象,一个只包含数据的类)。

但是,如果您确实需要annonymous类型来实现接口,请使用duck类型