-1

我有一些具有以下定义的方法;

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

为什么不允许这种演员表?你怎么能解决这个问题?我有大约 200 行代码,它们都适用于泛型,除了我需要对每个继承类(有 3 个)进行一个 LINQ 查询。我试图进行typeof检查,然后进行强制转换,然后执行适当的查询,但编译器不会让我进行强制转换...鉴于我刚刚检查以确保它T实际上是一个类型的InheritedClass实例绝不会失败,为什么编译器不让我这样做?

4

2 回答 2

2

You need to cast the variable to object and then back down to do this. 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.

InheritedClass instance = (InheritedClass)(object)instanceOfT;
于 2013-09-25T16:24:00.953 回答
1

因为实际 instanceOfT 的类型(我们称之为InheritedClassB)可能与InheritedClass.

鉴于我刚刚检查以确保 T 实际上是 InheritedClass 类型的实例

实际上,您只是在检查 T 是否扩展了 BaseClass。

编辑:这看起来像代码味道。你不能让具体类处理这个方法吗?所以每个具体类都有自己的实现,并且知道如何执行SomeMethod

于 2013-09-25T16:25:38.670 回答