不能隐式转换类型'XXX'& # 39; t # 39;
本文关键字:转换 类型 XXX 不能 | 更新日期: 2023-09-27 18:02:34
我尝试使用工厂模式来获取使用泛型的类的实例。不知道我错过了下面的代码。
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"
Update1
public interface IFactory
{
IService<IResult> GetService(string documentType);
}
public class MyFactory : IFactory
{
public IService<IResult> GetService(string documentType)
{
return new ServiceA<ResultA>();
}
}
假设您知道在每个IServiceA中,T都实现了IResult,那么您不需要使工厂泛型,而只需将其绑定为返回IService(如前面所示)。答案)。但是,为了使代码编译,您需要在MyFactory中强制转换返回值。GetService,如:
...
public interface IFactory
{
IService<IResult> GetService(string documentType);
}
public class MyFactory : IFactory
{
public IService<IResult> GetService(string documentType)
{
//Cast needed to address the error...
return (IService<IResult>) new ServiceA<ResultA>();
}
}
这段代码应该和你想要做的一样,并且应该可以正确编译。
每一个有T的地方,用IResult
代替
public interface IService<IResult>
{
IResult DoWork();
}
public class ServiceA<IResult> : IService<IResult> {}
public interface IFactory
{
IResult GetService(string documentType);
}
您需要强制转换您的结果。我也认为编译器需要编译你的"where"