简体   繁体   中英

Shadowing generic method class constraint

Is there a way store IReturn<T>... where T: class, IFeatureX in variable type IReturn<IFeatureX> or can you explain why this cannot be done?


Lets say that I have a container constructor:

public ContainerX(IReturn<IFeatureX> body) : this()
{
    Body = body;
}

I want to say that IFeatureX extends also class , I have tried changing the constructor to private and using:

public static ContainerX CreateInstance<T>(IReturn<T> instance) 
  where T : class, IFeatureX => new ContainerX { Body = instance };

However c# does not know that IReturn<T>... where T: class, IFeatureX is IReturn<IFeatureX> .

It seems that I cannot cast or safe cast it.

I cannot use object or dynamic because IFeatureX is actually IProtobufBody and it is a label interface that I use to make a integration test level guarantee that all assemblies that store instances in the container have a protobuf contract defined.

You simply need to make IReturn<T> covariant by declaring it as IReturn<out T> . You can read more about covariance and contravariance here .

This is a problem of covariance and contravariance ( see here ).

Lets say you have a class called Dog which inherits from Animal , consider the following code:

List<Dog> l = new List<Dog>();
List<Animal> la = l;
la.Add(new Giraffe()); // this is not allowed

This example shows why it is not allowed by default.

There are the keywords in and out that lets you use the contravariance and covariance like IReturn<in T> or IReturn<out T> .

When you use in , then you can store a IReturn<Object> object in a variable of type IReturn<Class> and define functions in IReturn that use T as input variable Type.

When you use out , then you can store a IReturn<Class> object in a variable of type IReturn<Object> and define functions in IReturn that use T as return Type.

If you need T to be an input variable type in some functions and a return type in other functions, then you can only work with the exact class.

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