与C#中的泛型类型作为关键字冲突编译时行为

当尝试使用不能转换的非泛型类型的C#“as”关键字时,编译器会给出类型无法转换的错误。

然而,当使用“as”关键字与通用类型时,编译器不会发出错误:

public class Foo { }

public class Bar<T> { }

public class Usage<T> {
   public void Test() {
      EventArgs args = new EventArgs();
      var foo = args as Foo;     // Compiler Error: cannot convert type
      var bar = args as Bar<T>;  // No compiler error
   }
}

我发现这个行为在一个更大的代码库中,缺少编译时错误导致运行时出现问题。

是设计冲突的行为吗?如果是这样,有没有人有什么洞察为什么?

在§7.10.11作为运算符C#5.0规范说:

In an operation of the form E as T, E must be an expression and T must be a reference type, a type parameter known to be a reference type, or a nullable type. Furthermore, at least one of the following must be true, or otherwise a compile-time error occurs:

  • An identity (§6.1.1), implicit nullable (§6.1.4), implicit reference (§6.1.6), boxing (§6.1.7), explicit nullable (§6.2.3), explicit
    reference (§6.2.4), or unboxing (§6.2.5) conversion exists from E to
    T.

  • The type of E or T is an open type.

  • E is the null literal.

因此,Foo提出错误,因为没有一个是真的。但是在第二种情况下,Bar< T>是一个开放类型,规范解释开放类型,§4.4.2打开和关闭类型:

An open type is a type that involves type parameters. More specifically:

  • A type parameter defines an open type. […]
http://stackoverflow.com/questions/28149927/conflicting-compile-time-behaviour-using-as-keyword-against-generic-types-in-c-s

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:与C#中的泛型类型作为关键字冲突编译时行为