开发者

Generic type casting

If i have a type and an object eg.:

 - Type someType (coming from somewhere, could be any class eg. MyClass.GetType())
 - Object someO开发者_如何转开发bject (eg. List<MyClass>())

and want to cast the object back to List<MyClass>. How should i do this?


You can't do this. Generics ensure compile-time safety. You cannot have compile time safety because you know the actual type only at runtime.


You have a runtime type and you want to perform a compile time cast. This is not possible. It is also not clear why you would want to do this in the first place. If you are interested in cases that require reflection, perhaps you should investigate that topic further.


There is no way to have compile-time typing a variable when you only receive the Type information at runtime.

This is different from generics since in generics you get the type information at compile time:

void MyFunc<T>(T thing)
{
  // T is passed in at compile time
}

In your case you are getting the type at runtime. So while you can't cast the member to the type the way you normally would you can reflect on the instance and call its members:

void MyFunc(object thing, Type type)
{
    var res = t.GetMethod("Add").Invoke(a, new []{"someArg"});
}


Casting means explicitly specifying the type you want to convert to. Since you don't know what your type is, you can't cast to it.

That doesn't mean you can't access the list. If you know the object you have is a list of something, you can cast it to the non-generic IList interface, which provides most of the methods and properties you need:

object obj = GetMyList();
IList list = (IList)obj;
object fifthItem = list[4];
list.RemoveAt(list.Count - 1);

If you describe the problem you're trying to solve rather than the solution you are trying to achieve, then more fitting solutions might be posted.


If you are trying to cast a runtime type at compile time, it is impossible as may said before me.
However, you could cheat a little (but don't use this technique excessively, it leads down a dark road...)

public void DoSomething<T>(List<T> object) where T : ....
{
 //do what you want here
}

public void CallIt(Type t, object o) //o is List<Foo>
{
 this.GetType().GetMethod("DoSomething").MakeGenericMethod(t).Invoke(o);
}

However I don't see any real benefit to this, as if you don't write any type constraint you gain nothing with using generics instead of objects and IList interface, and if you write any baseclass or interface there, you could just cast your object to that. (For example if you know that T implements IFoo, you could cast o to IList<IFoo> and have every benefit of List<Foo>...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜