Why does casting give CS0030, while “as” works?

前端 未结 3 615
情话喂你
情话喂你 2021-01-01 14:35

Suppose I have a generic method:

T Foo(T x) {
    return x;
}

So far so good. But I want to do something special if it\'s a Hashtable. (I

3条回答
  •  星月不相逢
    2021-01-01 15:06

    "The C# compiler only lets you implicitly cast generic type parameters to Object, or to constraint-specified types, as shown in Code block 5. Such implicit casting is type safe because any incompatibility is discovered at compile-time."

    See the section on Generics and Casting: http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx#csharp_generics_topic5

提交回复
热议问题