上溯造型到一个泛型类型 [英] Upcast to a Generic Type

查看:139
本文介绍了上溯造型到一个泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的类层次:

class A {
 /// stuff
}

class B : A {
 /// stuff
}

class C<T> : B {
  /// stuff
}



然后某处完全不同的我有以下三种方法:

Then somewhere completely different I have the following three methods:

public void foo(A a) {
}

// overload 1
public void bar(B b) {
}

// overload 2
public void bar<T>(C<T> ct) {
}

现在,不管是什么原因,我需要调用正确的从foo条中给出的实际类型A.也就是说,如果A实际上是B型的,我需要调用超负荷1,如果A实际上是C型(无论T可),我需要调用超负荷2.与的完整性,如果A不是b或C,什么也不做。

Now, for whatever reason, I need to call the "right" bar from foo given the actual type of A. That is, if A is actually of type B, I need to call overload 1 and if A is actually of type C (whatever T may be), I need to call overload 2. And for completeness, if A is not either B or C, do nothing.

现在,我使用的是Type类的IsAssignableFrom方法来决定是否上转换到b是可能的:

Right now, I am using the IsAssignableFrom method of the Type class to decide if the upconversion to B is possible:

public void foo(A a) {
   if (typeof(B).IsAssignableFrom(a)) {
      bar((B)a);
   }
}



不过,这需要在C变种为好。所以,问题是,我怎么执行这个向上转型?反射?动力学?我们使用在C#5,我不能使用。

But this takes in the C variants as well. So the question is, how do I perform this upcast? Reflection? dynamics? We are using .NET 4, so anything that was introduced in C# 5, I cannot use.

推荐答案

使用<$ C $介绍.NET 4中,所以任何C>动态。这将使方法解析发生在运行时,而不是编译时间,所以你会得到一个适合实际的实例类型最好的之一。

Use dynamic. It will make method resolution happen at runtime instead of compile time, so you'll get the one that fits actual instance type best.

bar((dynamic)value);

这篇关于上溯造型到一个泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆