I've class name which is in string format,I need to execute dynamically function and cast result into dynamically
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);
OR AlTERNAtely
public T CAST<T>(Object o){
//some mechanism
}
CAST<type >(result);
gives type or namespace name expected .. How do I Cast dynamically generated class type to generic type
Now I need to cast var result to a Type type (dynamic class). How?
I think what you need is Convert.ChangeType
. Below is a samples for invoking MyMethod
with string[]
parameters.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.