帮我解决类型问题

时间:2010-05-20 16:06:56

标签: 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
}
}

2 个答案:

答案 0 :(得分:6)

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

object ot = new TEST();
TEST t = cast<TEST>(ot);

答案 1 :(得分:1)

我会使用Generic方法:

public string SerializeObject<T>(object obj)
{
  if(obj is T)
    (obj as T).someMethod();
}