简体   繁体   English

从system.object上载到通用对象

[英]Upcasting to a generic object from system.object

I have some simple code which demonstrates my problem: 我有一些简单的代码演示了我的问题:

private void InitializeOther()
{
  List<Foo> list = new List<Foo>();
  Casting(list);
}

//in the "real" case I have no knowledge of o, other than it could be a List<>
private void Casting(object o)
{
  Type t = o.GetType();
  while (t.BaseType != typeof(Object))
  {
    if (t.IsGenericType && typeof(List<>) == t.GetGenericTypeDefinition())
    {
      //now I know that o is of type List<>. How can I now access List<> members from o?
      break;
    }
    t = t.BaseType;
  }
}

So, I can be sure that object o is of (or derived) from List<T> , but now I want to be able to access List<T> members on o, which means casting it up to List<Foo> . 因此,我可以确定对象o是List<T>的(或派生自),但现在我希望能够访问o的List<T>成员,这意味着将其强制转换为List<Foo> In my "real" case, I have no knowledge of Foo. 在我的“真实”案例中,我不了解Foo。

I'm pretty sure it can be done and if you know how to do it I'd be very grateful if you could share your knowledge with me! 我很确定这是可以做到的,如果您知道该怎么做,请与我分享您的知识,我将不胜感激!

A small hack will be to try and cast o to a non-generic IList , since List<T> implements both generic and non-generic interfaces. 一个小技巧是尝试将o转换为非通用IList ,因为List<T>实现了通用和非通用接口。 The same can be said of Collection<T> which is the most used base class for user collections. 可以说Collection<T>也是用户集合最常用的基类。

If this is not an option, you can always get along with reflective method invocation (late binding): MethodInfo.Invoke() , etc. 如果这不是一个选择,则您始终可以与反射方法调用(后期绑定)相处: MethodInfo.Invoke()等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM