c# - Set no type for a static method in a generic class -
not fan of java, java allows not setting types generic classes , in case threats type object
type. however, far know, c# enforces setting type of <t>
anytime generic class has instantiated or speaking used. however, let's have generic class, , need static method in there not rely on type of <t>
.
firstly, know can moved separate context or can set dummy type of <t>
, programming puzzle there way call without defining type of t
?
example:
class test<t> t: itestable { ... public static void createtestfile(string filename) {...} } test.createtestfile("test.txt");
this can done java , apparently can't in c#. wanna make sure.
java , c# implement generics differently:
java uses type erasure, means @ compile time, put in
<t>
erased , becomesobject
.something<foo>
,something<bar>
same type @ runtime, , wil equalsomething<object>
.c# uses run-time reification, meaning each type use distinct
t
, runtime generates new class altogether, using open generic version template (which means generates underlying native code once pert
call it).something<foo>
,something<bar>
2 unrelated types far clr concerned.
hopefully understand why difference important scenario. ignoring t
trivial in java, not easy in c#.
if don't need t
in code, use non-generic method:
abstract class test { public static void createtestfile(string filename) {...} } class test<t> : test t : itestable { ... }
here, that's better :)
also, note instance methods, can use covariant , contravariant interfaces loosen requirement known t
@ compile-time. instance, if use covariant interface, need know base type of t
.
Comments
Post a Comment