帮我解决类型问题

Ani*_*mde 1 c#

我想创建一个函数,它可以使用两个参数object和type,然后使用type参数将对象类型转换为适当的类型.那可能吗 ?我怎么能实现它?

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
}
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*orn 6

public T cast<T>(object obj)
{
   return (T)obj;
}

object ot = new TEST();
TEST t = cast<TEST>(ot);
Run Code Online (Sandbox Code Playgroud)