【发布时间】:2017-08-10 20:45:41
【问题描述】:
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>) 的变量。
【问题讨论】:
-
这里根本不清楚你在问什么。
-
@DavidG 好的,请稍等,我将添加示例。感谢您的反馈。
-
你指的是泛型吗?
-
所以不,你问的是不可能的,也不清楚你为什么要这样做。这对我来说有点像XY Problem。
-
Type 变量可以包含任何 Type 值,因为 Int32 变量可以包含任何 Int32 值。处理上没有区别
标签: c# inheritance reflection types syntax