[英]how to cast string to generic type
我有一个字符串格式的类名,我需要动态执行函数并将结果动态转换为
Type type = Type.GetType(method.NameSpace + "." + method.ClassName, false);
//
Type calledType = Type.GetType(namespaceName + "." + className + "," + assemblyName);
//this function return object type of class type which is I've created from string className
var result= calledType.InvokeMember(
methodName,
BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
null,
null,
obj);
或全部
public T CAST<T>(Object o){
//some mechanism
}
CAST<type >(result);
给出预期的类型或名称空间名称..如何将动态生成的类类型转换为泛型类型
现在,我需要将var结果转换为Type类型(动态类)。 怎么样?
我认为您需要的是Convert.ChangeType
。 以下是使用string[]
参数调用MyMethod
的示例。
public static string MyMethod(string s, int i, DateTime d)
{
return s + " " + i + " " + d.ToString();
}
public T Execute<T>()
{
//They are all strings in object array
object[] myparams = new object[] {"test","3","04/03/2012" };
Type[] types = this.GetType()
.GetMethod("MyMethod")
.GetParameters()
.Select(p=>p.ParameterType)
.ToArray();
object result =
this.GetType().InvokeMember(
"MyMethod",
BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
null,
this,
myparams.Select((s,i)=>Convert.ChangeType(s,types[i])).ToArray()
);
return (T)result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.