型別約束(類和介面)

型別約束能夠強制型別引數實現某個介面或類。

interface IType;
interface IAnotherType;

// T must be a subtype of IType
interface IGeneric<T>
    where T : IType
{
}

// T must be a subtype of IType
class Generic<T>
    where T : IType
{
}

class NonGeneric
{
    // T must be a subtype of IType
    public void DoSomething<T>(T arg)
        where T : IType
    {
    }
}

// Valid definitions and expressions:
class Type : IType { }
class Sub : IGeneric<Type> { }
class Sub : Generic<Type> { }
new NonGeneric().DoSomething(new Type());

// Invalid definitions and expressions:
class AnotherType : IAnotherType { }
class Sub : IGeneric<AnotherType> { }
class Sub : Generic<AnotherType> { }
new NonGeneric().DoSomething(new AnotherType());

多個約束的語法:

class Generic<T, T1>
    where T : IType 
    where T1 : Base, new()
{
}

型別約束的工作方式與繼承相同,因為可以將多個介面指定為泛型型別的約束,但只能指定一個類:

class A { /* ... */ }
class B { /* ... */ }

interface I1 { }
interface I2 { }

class Generic<T>
    where T : A, I1, I2
{
}

class Generic2<T>
    where T : A, B //Compilation error
{
}

另一個規則是必須將類新增為第一個約束,然後是介面:

class Generic<T>
    where T : A, I1
{
}

class Generic2<T>
    where T : I1, A //Compilation error
{
}

必須同時滿足所有宣告的約束才能使特定的通用例項化起作用。無法指定兩個或更多替代約束集。