2010-05-20 126 views
1

我想创建一个函数,它可以接受两个参数对象和类型,然后使用类型参数将对象转换为适当的类型。那可能吗 ?我怎么能实现它?帮我解决类型转换问题

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 
} 
} 

回答

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

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

@Anil Namde这种方法在这个例子中,如果你希望做进一步的阅读被称为'通用Methods'。 – Aren 2010-05-20 16:10:58

1

我会用这个泛型方法:

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