C#通用接口类型推断问题

时间:2011-06-07 17:27:25

标签: c# generics types inference

我不确定如何简明扼要地说出这个问题,而不仅仅举例说明了这一点:

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");

    }
}

2 个答案:

答案 0 :(得分:1)

问题似乎在这里:

// any way we can get the compiler to infer IThing<int> ?
var thing = f.Create("one");

没有。您需要明确指定类型:

var thing = f.Create<int>("one");

如果没有在方法中专门使用的参数,则无法推断返回类型。编译器使用传递给方法的参数来推断类型T,在这种情况下,它是单个字符串参数,没有类型T的参数。因此,没有办法为你推断这一点。

答案 1 :(得分:0)

不,您不能这样做,因为您的Create工厂方法的结果将在运行时根据参数的值进行评估。泛型用于编译时安全性,在您的情况下,您不能具有这样的安全性,因为参数值仅在运行时才知道。