Generics are a run-time concept. This is their primary difference from C++ templates, which are a compile-time concept.
Within the method Validate<T>
, T
is always unknown at compile-time, even when explicitly specified by the caller. The only thing Validate<T>
knows about T
is that it descends from Parent
.
More specifically, generics cannot be used to generate code. What you're trying would work under C++ because when C++ sees a call to Validate<ClassA>
, it actually recompiles Validate<T>
, so templates become a kind of code generation. Under C#, Validate<T>
is only compiled once, so generics cannot be used as a kind of code generation.
Under C++, the call to Validate<ClassA>
will instantiate the template at compile-time.
Under C#, the call to Validate<ClassA>
will instatiate the generic method at run-time.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…