类型Type
的变量可以包含任何类型。我需要的是一个变量,它只能包含继承特定类并实现特定接口的类型。这怎么指定?我曾尝试声明变量作为如何将类型类型限制为C#中的特定类型子集
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
(TS的一次性列表,而不是一个的列表中的任何类型的一次性)。
E.g.我将执行DisposableList<T>: List<T>, IDisposable
和AnotherDisposableListImplementation<T>: List<T>, IDisposable
类,我想要一个变量,它将能够存储typeof(DisposableList<Foo>)
和typeof(AnotherDisposableListImplementation<Foo>)
而不是typeof(Foo)
和typeof(List<Foo>)
。
目前尚不清楚你在不断地问这里。 – DavidG
@DavidG好吧,给我一点时间,我会添加例子。感谢您的反馈。 – Ivan
您是指泛型? –