简体   繁体   中英

Use constraint generic with interface

I have the following code where generic are involved:

    public class MyWorkerClass<T> : IWorkerContract<T> //in IWorkerContract also i have same generic constraint that i have in this class.
      where T: INeedAction, new()
    {
        public void DoWork ( T item )
        {
             //Loop on each property of item...
             if ( ..if current property value implement from INeedAction, then condition for recursion.. )
             {
                  this.DoWork ( currentPropertyValue as INeedAction);
                  //Get error -> "Can not convert INeedAction to T"
             }

Basically i have a woker that operate on an object 'A' (that need to implement the interface INeedAction). If any property of that object 'A' implement the same interface of the object itself (the i INeedAction interface) then i need to recurse with the same DoWork logic on that property too.

Strangelly i get that error that i does not understand: "Can not convert INeedAction to T" Why this, if i enforced that T must implement INeedAction?

Let's suppose that Foo and Bar both implement INeedAction , and Foo has a property of type Bar .

Then a MyWorkerClass<Foo> represents a work that is able to DoWork on a Foo . So far so good. However, look what happens when DoWork is called and it finds the Bar property. Since Bar implements INeedAction , you call

this.DoWork (bar as INeedAction);

Remember that this is still MyWorkerClass<Foo> - a thing that can only do work on Foo , but you are giving it a Bar to work with, That doesn't make sense? does it? This is why you can't pass an INeedWork to a parameter accepting T .

Note also that DoWork is not generic. It accepts a very specific type - T . This has to be the same T that is used in the class's type parameter.


Judging from your code, I don't think DoWork should be generic at all. It should accept an INeedWork .

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