C#: Casting from generic to value type -
i have method parses string , converts result generic type.
example (pseudo code):
let s string.. , value generic type if (generictype == int) value = int.parse(s); else if (generictype == float) value = float.parse(s);
the problem can't cast work:
t value; if (typeof(t) == typeof(float)) { var = 1.0f; value = // doesn't compile value = t; // doesn't compile value = (t)a; // doesn't compile }
what not understand know fact t float in code, can't write float it.
the goal parse numbers of different types strings. in each case, know sure type, there no question of handling passing wrong type, etc.
i trying see if can have single method, generic instead of several ones.
i can do:
value = parseint(s); value = parsefloat(s); etc...
but trying do:
value = parse<int>(s); value = parse<float>(s); etc...
once again, there no question of mismatch between type of 'value' , type passed generic.
i make generic class , override method parsing, thought there way in single method.
this compile , cast result t
:
value = (t)(object)a;
Comments
Post a Comment