1
我不知道如何詞組這個問題不簡潔只是給的例子所以這裏有雲:C#泛型接口類型推理問題
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。 – mnemosyn 2011-06-07 17:31:29
添加到答案中,如果沒有這種類型的「推理」,你的代碼就不應該編譯,因爲'Create'方法,尤其是因爲你的鑄件。 '新的ThingTwo()'不能被轉換成'IThing ',對'ThingOne'也是一樣的。它看起來像你需要一個動態類型的語言。或者你在設計中犯了(會造成)錯誤。 –
Snowbear
2011-06-07 17:36:56