using covariance on an interface …Runtime Error Unable to cast object of type 'derviedAService ' to type 'iBaseService`1[mybase]'

故事扮演 提交于 2021-02-05 09:39:59

问题


using System; 
using System.Collections.Generic;



namespace mymodels
{
public abstract class mybase
{
     public string v1 {get; set;}
}     


public class derivedA : mybase
{
      public string v2 {get; set;}
}


public class derivedB : mybase
{
      public string v2 {get; set;}
}

} 


namespace myservices 
{
interface iBaseService<T>  where T : mymodels.mybase
{
    T   Get ();
}



public class derviedAService : iBaseService<mymodels.derivedA>
{
    public derviedAService (){}

    public mymodels.derivedA Get()
    {
        mymodels.derivedA d = new mymodels.derivedA();

        return d;
    }
}   


public class derviedBService : iBaseService<mymodels.derivedB>
{
    public derviedBService (){}

    public mymodels.derivedB Get()
    {
        mymodels.derivedB d = new mymodels.derivedB();

        return d;
    }
}
}


namespace m
{
public class user
{

    myservices.iBaseService<mymodels.mybase> myservice = null;


    public user()
    {
        bool mode1 = true;

        if (mode1)
            myservice = (myservices.iBaseService<mymodels.mybase>)new myservices.derviedAService();
        else
            myservice = (myservices.iBaseService<mymodels.mybase>)new myservices.derviedBService();
    }   

}   
}   

I am trying to create a generic interface for a service that uses an abstract base class and derived classes. From the generic interface I am creating two implementations, one for each derived type. I have this setup, with out any problems....

My problem comes in my usage class..... For now I am trying to avoid using an IOC (unity, etc...) I wanted to setup the usage class to create an instance of the base service class and then type cast the instance to the selected derivedservice implementation ...

I believe this can be done with unity.... which I plan to use eventually... but for now I just wanted to do something simple to get up and running... My code compiles but at run time I get an error in the following pattern:

Unable to cast object of type 'derviedAService ' to type 'iBaseService`1[mybase]'.

I have tried to use an interface in place of the abstract class and this did not solve the problem.


回答1:


Your interface isn't covariant - it needs to be explicitly covariant when you declare it. So this:

interface iBaseService<T>  where T : mymodels.mybase

should be:

interface iBaseService<out T>  where T : mymodels.mybase

... except that you should also follow .NET naming conventions, using PascalCase for namespace, type and method names. Your code is very unconventional at the moment.



来源:https://stackoverflow.com/questions/22359142/using-covariance-on-an-interface-runtime-error-unable-to-cast-object-of-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!