【发布时间】:2016-08-15 21:21:26
【问题描述】:
我尝试使用工厂模式来获取使用泛型的类的实例。不知道我错过了下面的代码。
namespace ConsoleApplication1
{
public interface IResult
{
}
public class ResultA : IResult
{
public string P1 { get; set; }
}
public interface IService<T> where T : IResult
{
T DoWork();
}
public class ServiceA<T> : IService<T> where T : ResultA, IResult, new()
{
public T DoWork()
{
var t = new T();
t.P1 = "value1";
return t;
}
}
public interface IFactory
{
T GetService<T>(string documentType) where T : IService<IResult>;
}
public class MyFactory : IFactory
{
public T GetService<T>(string documentType) where T : IService<IResult>
{
// based on documenet type I will be returning the instances of service here
// im getting error at this line
return new ServiceA<ResultA>(); }
}
}
错误 1 无法隐式转换类型 'ConsoleApplication1.ServiceA' 到 'T'
更新1
这也不起作用
public interface IFactory
{
IService<IResult> GetService(string documentType);
}
public class MyFactory : IFactory
{
public IService<IResult> GetService(string documentType)
{
return new ServiceA<ResultA>();
}
}
【问题讨论】:
-
我可以将
ServiceFoo传递给T(只要它继承IService<IResult>)并期望返回该类型,但您正试图显式返回ServiceA。看到问题了吗? -
能否提供代码?
-
见下面的答案。你只是错过了一个演员。