已知类型的泛型参数我有一个接口:出,仅在运行时
public interface IOut<T>
{
void Get(out T output);
}
,并实现它的类:
public class Impl : IOut<string>, IOut<int>{
public void Get(out string output) { output = "string"; }
public void Get(out int output) { output = 12; }
}
我可以做以下就好:
public static void Main()
{
dynamic dImpl = new Impl();
string sOutput;
int iOutput;
dImpl.Get(out sOutput);
dImpl.Get(out iOutput);
Console.WriteLine(sOutput);
Console.WriteLine(iOutput);
}
我的问题是我只知道我需要的类型在运行时得到,所以我怎么样想打电话给我Get
代码是像这样:
public static void Main()
{
dynamic dImpl = new Impl();
var t = typeof(string);
t output;
dImpl.Get(out output);
Console.WriteLine(output);
}
现在,我知道这不会工作,我尝试了沉思执行主演:
public static T Cast<T>(object o) { return (T) o; }
,但我没有对象投射,我只有一个Type
。我试过默认值:
public static T Default<T>() { return default(T); }
但像string
等为null,并通过反射调用该方法时,事情默认:调用dImpl.Get(out defaulted)
时
var method = typeof(Program).GetMethod("Default").MakeGenericMethod(typeof(string));
var defaulted = method.Invoke(null, null);
defaulted
将是空的,运行时间不确定使用哪个超载。
所以,我正在寻找的是两种:一个 )好歹使用当前接口设置[首选] B)用不同的方式来实现目标
这是伟大的,我没有想过它会这样。 – 2013-03-06 13:20:14
''impl' in'method.Invoke(impl,parameters)'从哪里来? – bflemi3 2013-10-08 19:46:27
@ bflemi3 - 它只是为了成为Impl类的一个实例。我已经更新了答案。 – Lee 2013-10-08 20:24:54