简体   繁体   中英

C# generic parameters

Let's say I have some generic interface IMyInterface<TParameter1, TParameter2> .

Now, if I'm writing another class, generic on it's parameter T :

CustomClass<T> where T : IMyInterface

how should this be done?

(current code won't compile, because IMyInterface is dependent on TParameter, TParameter2 ) .


I assume it should be done like:

CustomClass<T, TParameter1, TParameter2> where T: IMyInterface<TParameter1,
                                                               TParameter2>

but I might be wrong, could you advice me please?

It's exactly as you have it, you need to specify the TParameter1 and TParameter2 generic arguments in a class which requires a generic constraint on IMyInterface :

public interface IMyInterface<TParameter1, TParameter2>
{ 
}

public class CustomClass<T, TParameter1, TParameter2> 
    where T : IMyInterface<TParameter1, TParameter2>
{

}

or you could have them fixed:

public class CustomClass<T> 
    where T : IMyInterface<string, int>
{

}

Do you really want to use it as a constraint (with the 'where' keyword)? Here are some examples of straight implementation:

interface ITwoTypes<T1, T2>

class TwoTypes<T1, T2> : ITwoTypes<T1, T2>

Or, if you know the type(s) your class will use, you don't need a type parameter on the class:

class StringAndIntClass : ITwoTypes<int, string>

class StringAndSomething<T> : ITwoTypes<string, T>

If you are using the interface as a constraint and don't know the types to specify explicitly, then yes, you need to add the type parameters to the class declaration, as you supposed.

class SomethingAndSomethingElse<T, TSomething, TSomethingElse> where T : ITwoTypes<TSomething, TSomethingElse>

class StringAndSomething<T, TSomething> where T : ITwoTypes<string, TSomething>

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