【发布时间】:2015-02-25 04:21:17
【问题描述】:
以下是我想要做的解释:
public class MyClass
{
public T GetFoo<T>() : where T : class, MyInterface
{
if (typeof(T) == typeof(Class1)
{
return new Class1() as T;
}
else if (typeof(T) == typeof(Class2))
{
return new Class2() as T;
}
else
{
return default(T);
}
}
private interface MyInterface {} // This is actually empty, it doesn't do anything except limit the types that can be passed to GetFoo()
public class Class1 : MyInterface
{
// Stuff
}
public class Class2 : MyInterface
{
// Other Stuff
}
// there are many more such classes that all inherit from MyInterface
}
所以,我有一个带有公共方法的公共类。该方法接受一个泛型类型参数。但我想限制它接受的 T 类型,所以这就是它使用 MyInterface 的原因。 当然,因为 MyInterface 是私有的,所以无法编译。它抛出“不一致的可访问性:约束类型比”错误更难访问。
但这就是我希望它以这种方式工作的原因:
Class1、Class2 等中的每一个都被声明为 public,以便其他人可以使用它们。但我想限制其他人能够声明自己的此类类并将它们传递给 GetFoo() 方法。因为这会破坏 GetFoo(),所以我希望 MyInterface 是私有的。
如果我公开 MyInterface,它当然会编译并且一切都会正常工作。但我需要能够防止其他人声明自己的类并继承 MyInterface 并将其传递给 GetFoo()。
我想允许调用者这样做:
Class1 userFoo = GetFoo<Class1>();
我想阻止来电者这样做:
Class UserClass : MyInterface {}
...
UserClass userFoo = GetFoo<UserClass>();
编辑:感谢所有非常快速的回复。是的,我知道这不是 Interface 的目的,它当时对我来说似乎很有意义。如果存在更优雅的解决方案,我当然愿意接受。
【问题讨论】:
-
如果界面是空的,你为什么要关心别人能不能看到呢?您不能以这种方式混合私有和公共。
-
所以...你让调用者有责任确保类型实现
MyInterface,但你不会给调用者一个机会来确保类型实现MyInterface? -
听起来你需要工厂模式。 msdn.microsoft.com/en-us/library/ee817667.aspx
-
调用者应该能够做到这一点:Class1 userCode = GetFoo
();调用者甚至不需要知道 MyInterface 存在。 -
@Wedge 约束验证(验证
Class1实现MyInterface)发生在调用站点,该接口不可见。
标签: c# generics types constraints