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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…