简体   繁体   中英

Generic method with specified types

Can I do something like this:

public void Foo<T>(int param) where T: MYCLASS1, MYCLASS2

To specify that T will only be MYCLASS1 or MYCLASS2 instance?

Thank you..

No, when you specify generic type constraints, the generic type argument must satisfy all the constraints, not just one of them. The code you wrote means that T must inherit both MYCLASS1 and MYCLASS2 , which is not possible since C# doesn't support multiple inheritance. The generic type constraints can be a combination of:

  • a base class (only one allowed)
  • one or several interfaces
  • the new() constraint (ie the type must have a parameterless constructor)
  • either struct or class (but not both, since a type can't be a value type and a reference type)

You cannot do that.

While adding constraints on a generic type you can list only one class and others have to be interfaces.

This is a valid constraint -

public void Foo<T>(int param) where T: MyClass1, IInterface1, IInterface2

But not this

public void Foo<T>(int param) where T: MyClass1, MyClass2

This is logical, because when you declare a variable of type Foo such as Foo<MyType> , your MyType can derive from MyClass1 , IInterface1 and MyInterface2 but it cannot derive from both MyClass1 and MyClass2 .

No, generic constraints are always ANDed together. You will have to do a runtime check:

public void Foo<T>(int param) {
    if (typeof(T) != typeof(MyClass1) && typeof(T) != typeof(MyClass2))
        throw new ArgumentException("T must be MyClass1 or MyClass2");
    // ...
}

As Thomas points out, you cannot do this. What you can do however is this:

public void Foo<T>(int param) where T: IMyInterface

As long as you know that both MYCLASS1 and MYCLASS2 implement IMyInterface

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM