如何将字符串强制转换为泛型类型
本文关键字:转换 泛型类型 字符串 | 更新日期: 2023-09-27 18:29:46
我有字符串格式的类名,我需要动态执行函数并将结果转换为动态
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类型(动态类)。怎样
我认为您需要的是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;
}