2017-03-19 48 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

相关问题