我有以下代码:
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(),有没有其他方法来使用这个函数?
发布于 2009-10-22 20:53:37
你可以,但它涉及到反射,但你可以做到。
typeof(ClassExample)
.GetMethod("DoSomething")
.MakeGenericMethod(p.DisplayType)
.Invoke(this, new object[] { p.Name, p.Value });这将查看包含类的顶部,获取方法信息,创建一个具有适当类型的泛型方法,然后您可以对其调用Invoke。
发布于 2009-10-22 20:53:13
this.GetType().GetMethod("DoSomething").MakeGenericMethod(p.Value.GetType()).Invoke(this, new object[]{p.Name, p.Value});应该行得通。
发布于 2009-10-22 20:53:41
泛型类型不能在运行时以您希望的方式在这里指定。
最简单的选择是添加DoSomething的非泛型重载,或者简单地调用DoSomething<object>并忽略p.DisplayType。除非SendToDatabase依赖于value的编译时类型(它可能不应该依赖于编译时类型),否则给它一个object应该没有什么问题。
如果你不能做到这一点,你将不得不使用反射来调用DoSomething,而且你的性能会受到很大的影响。
https://stackoverflow.com/questions/1606966
复制相似问题