c# - Can't use an instance variable of non-generic class inheriting from a generic class with specified type -
i created classes these:
abstract class aclass1<t> { // code here } class class2 : aclass1<int> { // code here } class class3 : aclass1<float> { // code here } class class4<t> : aclass1<t> { // code here }
so far works. in class i'd have:
... aclass1<t> variable;
and depending on specific needs set variable either:
variable = new class2();
or
variable = new class3();
or sometimes:
variable = new class4<t>();
this produces compile error no possible cast or else tried. @ moment changed inheriting classes generic like:
class class2<t> : aclass1<t> { // code here }
but doesn't feel right, because there no generic methods or there.
the question right way it, why, , why can't using original way?
by way .net 2.0 i'm doing inside unity3d.
to more clear:
i have specific cases e.g. int type want handle specifically, there other i'd have generic class for. created subclasses specifcally handle types , have generic subclass use when there no specific implementation type. when create specific class type should not generic handles 1 type.
the compiler trying ensuring don't perform assignments aren't guaranteed work. isn't legal:
void foo<t>() { ... if (typeof(t) == typeof(int)) { aclass1<t> variable = new class2(); } ... }
and that's because class2
compatible aclass1<int>
-- if don't know t
is, can't in general it's compatible aclass1<t>
. in code above, it's certainty conversion possible, compiler isn't sophisticated enough determine code safe -- in general, without if
, wouldn't be. casting doesn't work either, because there no conversion class2
aclass1<t>
arbitrary t
.
to make work, have forego compile-time type checking , force runtime conversion -- it's legal cast , object
@ compile time:
aclass1<t> variable = (aclass1<t>) (object) new class2();
if wrong, code fail @ runtime invalidcastexception
.
this approach dubious because raises question of why using generics (a compile-time type feature) , circumventing them in actual code. code has reviewed see if appropriate solution. possible alternatives introducing non-generic base class, using containment generic types, or not using generics (if you're using float
, int
, generic base class adding anything?)
Comments
Post a Comment