類型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
您是指泛型? –