我有以下代码:通用方法中执行一个运行时类型
public class ClassExample
{
void DoSomthing<T>(string name, T value)
{
SendToDatabase(name, value);
}
public class ParameterType
{
public readonly string Name;
public readonly Type DisplayType;
public readonly string Value;
public ParameterType(string name, Type type, string value)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
if (type == null)
throw new ArgumentNullException("type");
this.Name = name;
this.DisplayType = type;
this.Value = value;
}
}
public void GetTypes()
{
List<ParameterType> l = report.GetParameterTypes();
foreach (ParameterType p in l)
{
DoSomthing<p.DisplayType>(p.Name, (p.DisplayType)p.Value);
}
}
}
现在,我知道我不能执行DoSomething的() 有没有使用此功能的任何其他方式?
只有一个catch,p.Value是一个字符串,所以调用将失败,除非p.DisplayType碰巧是typeof(string)。 – stevemegson 2009-10-22 13:39:57
惭愧这是唯一的解决方案,meh – 2009-11-16 21:54:58
嗯,我想你可以在4.0中使用动态,它会推断正确的泛型参数类型,但我还没有机会验证它。并不是说它在封面上做的和上面的代码不同,但也许是这样。 – 2009-11-16 22:11:11