简体   繁体   中英

Generic method with many types

If I want a generic method to have many generic types, eg up to 16.

Do I have to overload the method 16 times or is there any smarter way to do this?

public interface IMyInterface { }

public class MyClass {
    public void MyMethod<T1>() where T1 : IMyInterface { }
    public void MyMethod<T1, T2>() where T1 : IMyInterface where T2 : IMyInterface { }
    public void MyMethod<T1, T2, T3>() where T1 : IMyInterface where T2 : IMyInterface 
                                       where T3 : IMyInterface { }
    public void MyMethod<T1, T2, T3, T4>() where T1 : IMyInterface where T2 : IMyInterface 
                                           where T3 : IMyInterface where T4 : IMyInterface { }
    // All the way to T16...
    // Is there any smarter way of doing this
    // instead of having to write it 16 times?
}

if you look at the documentation of Action<T1, T2, ....> it seems that you need to implement all overloads singlehandedly.

Here is the reference source of it. As you see it is done as in your example.

A more detailed answer as to why a params equivalent does not exist can be found by Jon Skeet here . It states:

"Fundamentally Func<T> and Func<T1, T2> are entirely unrelated types as far as the CLR is concerned, and there's nothing like params to specify multiple type arguments."

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