简体   繁体   中英

How to Call this Generic Method with a Generic Type?

I have this code at the moment:

Method1<Class1<Class2>>();

public void Method1<T>()
{
    // process
}

Class1 needs a generic type itself ( Class2 ).

I have to call the Method1 about 10 times for all of which Class2 would be the same type.

So how could I call Method1 with something like following:

Method1<Class1<J>>();

Where J is a generic type itself for the Class1 .

Yes.

The same applies here:

IList<IEnumerable<string>>

You can use the using directive in your class file to alias either one or both of your classes.

using J = Class2;
using MyClass = Class1<Class2>;

(Apply appropriate namespaces as necessary to the class names, like Foo.Bar.Class1 , etc.)

Now you can invoke your method with any of the following statements

Method1<Class1<Class2>>();
Method1<Class1<J>>();
Method1<MyClass>();

Or even cleaner code as using using : create a real subclass:

class SpecializedClass1:Class1<Class2>
{
    /* empty or do whatever makes sense in this specialized variant */
}

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