2017-03-19 51 views
0

類型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>, IDisposableAnotherDisposableListImplementation<T>: List<T>, IDisposable類,我想要一個變量,它將能夠存儲typeof(DisposableList<Foo>)typeof(AnotherDisposableListImplementation<Foo>)而不是typeof(Foo)typeof(List<Foo>)

+2

目前尚不清楚你在不斷地問這裏。 – DavidG

+0

@DavidG好吧,給我一點時間,我會添加例子。感謝您的反饋。 – Ivan

+0

您是指泛型? –

回答

0

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和的子類型。

1

我相信這是你在找什麼

public class EstentedList<Type> where Type:List<T>,IDisposable 
{ 

} 

你可以使用這個類作爲類型爲你的變量

+1

這是如何阻止某個特定類型存儲在'Type'變量中的? – DavidG

相關問題