1

例を挙げずにこの質問を簡潔に表現する方法がわからないので、次のようにします。

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

    }
}
4

2 に答える 2

1

質問はここにあるようです:

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

いいえ。タイプを明示的に指定する必要があります。

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

メソッドで特に使用されるパラメーターがなければ、戻り値の型を推測することはできません。コンパイラは、メソッドに渡されたパラメーターを使用して type を推測しますT。この場合、これは単一の文字列パラメーターであり、 type のパラメーターはありませんT。そのため、これを推測する方法はありません。

于 2011-06-07T17:31:03.880 に答える
0

いいえ、これはできません。Createファクトリ メソッドの結果は、パラメーターの値に基づいて実行時に評価されるためです。ジェネリックはコンパイル時の安全性のためのものであり、あなたの場合、パラメーター値は実行時にのみ知られるため、そのような安全性を持つことはできません。

于 2011-06-07T17:29:59.430 に答える