我有以下类和接口:
public interface IThing
{
string Name { get; }
}
public class Thing : IThing
{
public string Name { get; set; }
}
public abstract class ThingConsumer<T> where T : IThing
{
public string Name { get; set; }
}
现在,我有一个工厂,它将返回从ThingConsumer派生的对象,如下所示:
public class MyThingConsumer : ThingConsumer<Thing>
{
}
我的工厂现在看起来像这样:
public static class ThingConsumerFactory<T> where T : IThing
{
public static ThingConsumer<T> GetThingConsumer(){
if (typeof(T) == typeof(Thing))
{
return new MyThingConsumer();
}
else
{
return null;
}
}
}
我遇到了这个错误:Error 1 Cannot implicitly convert type 'ConsoleApplication1.MyThingConsumer' to 'ConsoleApplication1.ThingConsumer<T>'
有人知道如何完成我在这里尝试的东西吗?
谢谢!
克里斯
发布于 2012-09-08 03:29:54
如果您将ThingConsumer<T>
作为接口而不是抽象类,那么您的代码将按原样工作。
public interface IThingConsumer<T> where T : IThing
{
string Name { get; set; }
}
编辑
还需要再做一次改变。在ThingConsumerFactory
中,强制转换回返回类型IThingConsumer<T>
return (IThingConsumer<T>)new MyThingConsumer();
发布于 2012-09-08 04:06:18
编译器在从MyThingConsumer
到ThingConsumer<T>
的转换中遇到了困难,即使是T:IThing
、MyThingConsumer:Thingconsumer<Thing>
和Thing:IThing
也是如此。对于它来说,这是一个相当多的障碍!
如果您使用return new MyThingConsumer() as ThingConsumer<T>;
而不是直接转换,则代码可以正常工作。您知道结果永远不会是null
,编译器很高兴,因为它在运行时得到了正确类型的返回值。
编辑:这里是我用来测试的完整代码(用Snippy编写):
public interface IThing
{
string Name { get; }
}
public class Thing : IThing
{
public string Name { get; set; }
}
public abstract class ThingConsumer<T> where T : IThing
{
public string Name { get; set; }
}
public class MyThingConsumer : ThingConsumer<Thing>
{
}
public static class ThingConsumerFactory<T> where T : IThing
{
public static ThingConsumer<T> GetThingConsumer()
{
if (typeof(T) == typeof(Thing))
{
return new MyThingConsumer() as ThingConsumer<T>;
}
else
{
return null;
}
}
}
...
var thing = ThingConsumerFactory<Thing>.GetThingConsumer();
Console.WriteLine(thing);
发布于 2012-09-08 03:12:42
我相信你需要这样定义你的类:
public class MyThingConsumer<Thing> : ThingConsumer
原因是ThingConsumer
在其定义中已经键入了以下内容:where T : IThing
现在,您可以调用return new MyThingConsumer<T>();
。
这又应该与ThingConsumer<T>
的预期返回类型相匹配
编辑
很抱歉造成混乱,以下是应该起作用的方法:
public class MyThingConsumer<T> : ThingConsumer<T> where T : IThing
和
return new MyThingConsumer<T>();
https://stackoverflow.com/questions/12324020
复制相似问题