从 system.object 向上转换为通用对象

发布于 2024-07-13 22:39:25 字数 800 浏览 3 评论 0原文

我有一些简单的代码来演示我的问题:

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

所以,我可以确定对象 o 是来自(或派生) List,但现在我希望能够访问 List o 上的成员,这意味着将其强制转换为 List。 在我的“真实”案例中,我对 Foo 一无所知。

我很确定这是可以做到的,如果您知道如何做到这一点,如果您能与我分享您的知识,我将非常感激!

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>. In my "real" case, I have no knowledge of 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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ぃ双果 2024-07-20 22:39:25

一个小技巧是尝试将 o 转换为非泛型 IList,因为 List 实现了泛型和非泛型接口。 对于用户集合最常用的基类 Collection 也是如此。

如果这不是一个选项,您始终可以使用反射方法调用(后期绑定):MethodInfo.Invoke() 等。

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. The same can be said of Collection<T> which is the most used base class for user collections.

If this is not an option, you can always get along with reflective method invocation (late binding): MethodInfo.Invoke(), etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文