我的类名是字符串格式,我需要动态执行函数并将结果转换为动态
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);
或AlTERNAtely
public T CAST<T>(Object o){
//some mechanism
}
CAST<type >(result);
给出预期的类型或命名空间名称.. 如何将动态生成的类类型转换为泛型类型
现在我需要将var结果转换为Type类型(动态类)。怎么样?
答案 0 :(得分:0)
我认为你需要的是Convert.ChangeType
。以下是使用MyMethod
参数调用string[]
的示例。
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;
}