类型为 Type
的变量可以包含任何类型。我需要的是一个变量,它只能包含继承特定类并实现特定接口的类型。如何指定?我尝试将变量声明为
Type: MyClass, IMyInterface theTypeVariable;
和作为
Type<MyClass, IMyInterface> theTypeVariable;
但两者都不起作用。
正确的方法是什么?
例如
class A {...}
class B {...}
interface IC {...}
interface ID {...}
class E: B, IC {...}
class F: B, IC, ID {...}
class G: ID {...}
...
// This following line invalid actually,
// so it is pseudocode of a kind
// the syntactically and semantically correct form of this is the question
Type: B, IC theTypeVariable; // or Type<B, IC> theTypeVariable // perhaps
theTypeVariable = typeof(E); // This assignment is to be valid.
theTypeVariable = typeof(F); // This assignment is to be valid.
theTypeVariable = typeof(A); // This assignment is to be invalid.
theTypeVariable = typeof(B); // This assignment is to be invalid.
theTypeVariable = typeof(IC); // This assignment is to be invalid.
theTypeVariable = typeof(G); // This assignment is to be invalid.
举一个更明确的例子:我可能想声明一个类型变量,该变量只能包含任何扩展List<T>
和实现IDisposable
的类型(T 的一次性列表,而不是一次性列表(。
例如,我将实现DisposableList<T>: List<T>, IDisposable
和AnotherDisposableListImplementation<T>: List<T>, IDisposable
类,我想要一个能够存储typeof(DisposableList<Foo>)
和typeof(AnotherDisposableListImplementation<Foo>)
但不能存储typeof(Foo)
或typeof(List<Foo>)
的变量。
这就是你要找的
public class EstentedList<Type> where Type:List<T>,IDisposable
{
}
您可以将此类用作变量的类型
Type
包含有关类型的元数据;它是反射API的一部分。这是无效的:
Type x = 5;
Type y = "Hello Sailor!";
要使类型U
(子类型为 T
并实现接口I
可以使用泛型:
... Foo<U>(...)
where U : T, I
{
U myvar;
}
您可以通过以下方式创建新类型:
class MyType : MyClass, IMyInterface
{
private MyClass A;
private IMyInterface B;
private MyType(MyClass a, IMyInterface b)
{
A = a;
B = b;
}
public static MyType Create<U>(U x)
where U : MyClass, IMyInterface
{
return new MyType(x, x);
}
// Implementations of MyClass and IMyInterface
// which delegate to A and B.
}
现在,类型为 MyType
的变量是 MyClass
和 IMyInterface
的子类型。