【发布时间】:2009-01-31 01:47:24
【问题描述】:
我有以下情况:
// A public interface of some kind
public interface IMyInterface {
int Something { get; set; }
}
// An internal class that implements the public interface.
// Despite the internal/public mismatch, this works.
internal class MyInternalConcrete : IMyInterface {
public int Something { get; set; }
}
// A generic class with an interface-restricted type parameter.
// Note that the constraint on T uses the *public* interface.
// The instance is *never* exposed as a public, or even protected member.
public class MyClass<T> where T : IMyInterface, new() {
T myInterfaceInstance;
public MyClass() {
myInterfaceInstance = new T();
}
}
// Attempting to implement concrete class... Inconsistent Accessibility Error!
public class MySpecificClass : MyClass<MyInternalConcrete>
{
}
在尝试实现 MySpecificClass 时,出现错误:
可访问性不一致:基类“App1.MyClass”的可访问性低于类“App1.MySpecificT”
奇怪的是 MyInternalConcrete 尽管是 internal,但仍然可以实现 public 接口。并且由于它实现了接口,那么它应该可用作 MyClass 的类型参数 - 因为 T 受限于公共接口而不是内部类。
如果 MyClass 暴露了 T,我会理解它会失败,就像我们不使用泛型会失败一样:
public class MyClass<T> where T : IMyInterface, new() {
T myInterfaceInstance;
public MyClass() {
myInterfaceInstance = new T();
}
// This will fail with an internal T - inconsistent accessibility!
public T Instance {
get { return myInterfaceInstance; }
}
}
和上面一样,但是没有泛型:
public class MyNonGenericClass {
MyInternalConcrete myInterfaceInstance;
public MyNonGenericClass() {
myInterfaceInstance = new MyInternalConcrete();
}
// This will fail - inconsistent accessibility!
// but removing it works, since the private instance is never exposed.
public MyInternalConcrete Instance {
get { return myInterfaceInstance; }
}
}
这是 C# 泛型的限制,还是我只是误解了泛型如何工作的基本原理?
I also posted this thread on MSDN,但我被解雇了,因为我不知道我在说什么。我的担心是否有效?
【问题讨论】:
标签: c# .net generics interface