C# generic interface type inference question
I'm not sure how to phrase this question concisely without just giving the example so here goes:
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"))开发者_如何学JAVA
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");
}
}
The question appears to be here:
// any way we can get the compiler to infer IThing<int> ?
var thing = f.Create("one");
No. You would need to explicitly specify the type:
var thing = f.Create<int>("one");
You can't infer the return type without having a parameter used specifically in the method. The compiler uses the parameters passed to the method to infer the type T
, and in this case, it's a single string parameter, with no parameters of type T
. As such, there's no way to have this inferred for you.
No, you can't do this because the result of your Create
factory method will be evaluated at runtime based on the value of the parameter. Generics are for compile-time safety and in your case you cannot have such safety because the parameter value will be known only at runtime.
精彩评论