【发布时间】:2011-06-07 17:27:24
【问题描述】:
我不知道如何简洁地表达这个问题而不只是给出例子,所以这里是:
public interface IThing<T>
{
void Do(T obj);
}
public class ThingOne : IThing<int>
{
public void Do(int obj)
{
}
}
public class ThingTwo : IThing<string>
{
public void Do(string obj)
{
}
}
public class ThingFactory
{
public IThing<T> Create<T>(string param)
{
if (param.Equals("one"))
return (IThing<T>)new ThingOne();
if (param.Equals("two"))
return (IThing<T>)new ThingTwo();
}
}
class Program
{
static void Main(string[] args)
{
var f = new ThingFactory();
// any way we can get the compiler to infer IThing<int> ?
var thing = f.Create("one");
}
}
【问题讨论】:
-
这不是类型推断 - 您的返回类型不是静态的,即事先不知道是否会返回 TypeOne 或 TypeTwo。
-
添加到答案中,由于
Create<T>方法,尤其是因为您的铸件,您的代码甚至不应该在没有那种“推理”类型的情况下编译。new ThingTwo()不能转换为IThing<T>,ThingOne也是如此。看起来您需要一种动态类型的语言。或者你在设计中犯了(即将犯)错误。
标签: c# generics types inference