C# 帮我解决打字问题

C# 帮我解决打字问题,c#,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 typ

我想创建一个函数,它可以接受两个参数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
}
}
publictcast(objectobj)
{
返回(T)obj;
}
对象ot=新测试();
试验t=铸件(ot);
public T cast(对象obj)
{
返回(T)obj;
}
对象ot=新测试();
试验t=铸件(ot);

对此,我将使用通用方法:

public string SerializeObject<T>(object obj)
{
  if(obj is T)
    (obj as T).someMethod();
}
公共字符串序列化对象(对象obj)
{
if(obj是T)
(obj as T).someMethod();
}

对此,我将使用通用方法:

public string SerializeObject<T>(object obj)
{
  if(obj is T)
    (obj as T).someMethod();
}
公共字符串序列化对象(对象obj)
{
if(obj是T)
(obj as T).someMethod();
}

@Anil Namde如果您希望进一步阅读,本例中的此方法称为
通用方法
。@Anil Namde如果您希望进一步阅读,本例中的此方法称为
通用方法