只有一种实现的简单接口的匿名类型
Anonymous types for simple interfaces with only one implementation
假设我有以下接口:
public interface IMyInterface {
A MyA { get; }
B MyB { get; }
C MyC { get; }
}
A
、B
和C
是三个不相关的类,不以任何方式实现IMyInterface
。
现在假设我将只有一个该接口的实现。我可能想出于模拟目的创建它,即使它只是由属性组成。
我设计了以下工厂:
public static class MyManagerFactory {
public static IMyManager CreateMyManager() {
//Return the implementation
}
}
我不想为属性的实现创建一个全新的文件和类型,所以我一直在寻找一个匿名类型:
var anon = new {
MyA = new A(),
MyB = new B(),
MyC = new C()
};
但我不能 return anon
因为它是 object
类型并且编译器不知道我正在实现我的接口。
所以我想到了演员表:
IMyInterface casted = anon as IMyInterface;
但这也不会编译,说明:
Cannot convert type 'AnonymousType#1' to 'IMyInterface' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion.
我认为 as
转换应该在运行时完成,如果(出于任何原因)失败,它只会 return null
.
但是这个错误是编译时的。
如何 return 一个 IMyInterface
实例?
这可能是个不错的功能,但目前 C# 不支持匿名对象上的匿名实现接口。
如果您查找更多信息,您会看到 Java 具有此功能(例如,请参阅 Whosebug 中的此问答:How can an anonymous class use "extends" or "implements"?)。
至少 C# 6 不会包含此功能。从我的角度来看,它可能非常有用,并且以我的拙见,这是我将窃取以在 C# 中实现的独特 Java 功能。
这是不可能的,因为该类型没有实现接口。
它只有接口的方法 "by coincidence"
C# 不会查看方法是否存在,它会检查类型是否定义为实现接口。
I might have wanted to create it for mocking purposes,
I don't want to create a whole new file and type for just an implementation of properties, so I was looking for an anonymous type:
如果只是为了模拟目的,那么您可以只创建该接口的嵌套私有实现,不需要全新的文件
public class MyClassTests
{
private class MyDummyImplementation : IMyInterface { ... }
[Fact]
public void Test()
{
var x = new MyDummyImplementation();
}
}
假设我有以下接口:
public interface IMyInterface {
A MyA { get; }
B MyB { get; }
C MyC { get; }
}
A
、B
和C
是三个不相关的类,不以任何方式实现IMyInterface
。
现在假设我将只有一个该接口的实现。我可能想出于模拟目的创建它,即使它只是由属性组成。
我设计了以下工厂:
public static class MyManagerFactory {
public static IMyManager CreateMyManager() {
//Return the implementation
}
}
我不想为属性的实现创建一个全新的文件和类型,所以我一直在寻找一个匿名类型:
var anon = new {
MyA = new A(),
MyB = new B(),
MyC = new C()
};
但我不能 return anon
因为它是 object
类型并且编译器不知道我正在实现我的接口。
所以我想到了演员表:
IMyInterface casted = anon as IMyInterface;
但这也不会编译,说明:
Cannot convert type 'AnonymousType#1' to 'IMyInterface' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion.
我认为 as
转换应该在运行时完成,如果(出于任何原因)失败,它只会 return null
.
但是这个错误是编译时的。
如何 return 一个 IMyInterface
实例?
这可能是个不错的功能,但目前 C# 不支持匿名对象上的匿名实现接口。
如果您查找更多信息,您会看到 Java 具有此功能(例如,请参阅 Whosebug 中的此问答:How can an anonymous class use "extends" or "implements"?)。
至少 C# 6 不会包含此功能。从我的角度来看,它可能非常有用,并且以我的拙见,这是我将窃取以在 C# 中实现的独特 Java 功能。
这是不可能的,因为该类型没有实现接口。 它只有接口的方法 "by coincidence"
C# 不会查看方法是否存在,它会检查类型是否定义为实现接口。
I might have wanted to create it for mocking purposes,
I don't want to create a whole new file and type for just an implementation of properties, so I was looking for an anonymous type:
如果只是为了模拟目的,那么您可以只创建该接口的嵌套私有实现,不需要全新的文件
public class MyClassTests
{
private class MyDummyImplementation : IMyInterface { ... }
[Fact]
public void Test()
{
var x = new MyDummyImplementation();
}
}