c# - Why Is It That Generics Constraint Can't Be Casted to Its Derived Type? -


It is quite upset to find that the generic barrier can not be covered in its type of type.

Suppose I have the following code:

  Public abstract class base class {public int version {get {return 1; }} Public String FixString {get; Set; } Public Base Class () {FixString = "hello"; } Public Virtual Ink GetBaseVersion () {Return version; }} Public Category DeriveClass: Base Class {Public New Int Edition {get {return 2; }}}  

And it seems, this method will return a compilation error:

  Public Zero Freakonson & lt; T & gt; (T based class) {if (baseClass GateType () == Type (DeriveClass) var derivedMe = (DeriveClass) baseClass;}  

I baseClass to Object before I can put it in the DerivedClass , ie,

  free public conversion & lt; T & gt; (T baseClass) I {if (baseClass.GetType () = = Type (DeriveClass) var derivedMe = (DeriveClass) ((object) baseClass);}  

I feel very ugly. ?

First of all, you need to type the base type of a derived type This is not the only way to do the work.

Second, why it works through the object , because you compile time type The compiler can check that a B AseType can not be inserted on DeriveType .but when a variable is object So the compiler leaves you by assuming that you know what you are doing. Even if it is compiled, then there will be an accident during code execution.


Comments