我有以下代碼:通用方法中執行一個運行時類型
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