I would like to create a function which can take two arguments object and type and then type cast the object to appropriate type using the type parameter. Is that possible ? how can i achieve it ?
public class TEST
{
public int test;
}
object ot = new TEST();
Type type = typeof(TEST);
TEST t = (type)ot;
//Function will be something like this Type t is开发者_开发百科 type we get using typeof()
public string SearializeObject(Object obj, Type t)
{
//check if obj is of type t
if(obj is of type t){
//cast obj to type t to read it
((Type t)obj).someMethod
}
}
public T cast<T>(object obj)
{
return (T)obj;
}
object ot = new TEST();
TEST t = cast<TEST>(ot);
I would use a Generic method for this:
public string SerializeObject<T>(object obj)
{
if(obj is T)
(obj as T).someMethod();
}
精彩评论