开发者

help me with typecasting problem

开发者 https://www.devze.com 2022-12-31 23:52 出处:网络
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 ?

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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消