简体   繁体   English

为什么不能将通用类型转换为继承类型?

[英]Why can't I cast generic type to inheriting type?

I have some method with the following definition; 我有一些定义如下的方法;

 public void SomeMethod<T>() where T : BaseClass, new()
 {
      InheritedClass instance = (InheritedClass)instanceOfT; //won't compile
 }

Why is that cast not allowed? 为什么不允许该演员? How can you get around this? 您如何解决这个问题? I have about 200 lines of code which is all suited for generics except I need a one LINQ query for each of the inheriting classes (there are 3). 我有大约200行代码,这些代码都适合于泛型,除了我需要对每个继承类(一个3)进行一个LINQ查询。 I was trying to do a typeof check, then follow that with a cast, then execute the appropriate query but the compiler won't let me do the cast... Given I just checked to ensure that T is in fact an instance of type InheritedClass there is no way it would fail, why won't the compiler let me do it? 我正在尝试进行typeof检查,然后进行typeof ,然后执行适当的查询,但是编译器不允许我进行强制类型转换...鉴于我只是检查以确保T实际上是类型的实例InheritedClass没有办法失败,为什么编译器不让我这样做呢?

You need to cast the variable to object and then back down to do this. 您需要将变量强制转换为object ,然后再向下执行此操作。 As it is the compiler believes that there is no possible way that the cast could succeed, but it doesn't ever apply that check to variables of type object . 因为正是编译器认为,强制转换没有成功的可能方法,但是它从来没有将检查应用于object类型的变量。

InheritedClass instance = (InheritedClass)(object)instanceOfT;

Because the actual instanceOfT's type (let's call it InheritedClassB ) may not be related to InheritedClass . 因为实际的instanceOfT的类型(我们称它为InheritedClassB )可能与InheritedClass不相关。

Given I just checked to ensure that T is in fact an instance of type InheritedClass 给定我只是检查以确保T实际上是InheritedClass类型的实例

Actually, you're only checking that T extends BaseClass. 实际上,您只是在检查T是否扩展了BaseClass。

Edit: This looks like a code smell.. Can't you let the concrete class handle this method? 编辑:这看起来像是代码的味道。您不能让具体的类处理此方法吗? So each concrete class would have its own implementation, and know how to perform SomeMethod . 因此,每个具体类都有其自己的实现,并且知道如何执行SomeMethod

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

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