c# - Is there a way to get the Generic Type from an Extension method? -
consider method:
public static tresult castto<t, tresult>(this t arg) { typeconverter typeconverter = typedescriptor.getconverter(typeof(t)); bool? converter = typeconverter?.canconvertto(typeof(tresult)); if (converter != null && converter == true) return (tresult)typeconverter.convertto(arg, typeof(tresult)); else return default(tresult); }
is there way set generic type extension method, mean, instead call:
string s = "1"; s.castto<string, int>();
something input type directly class who's calling. i'm pretty new c# , want know issue.
you can ommit type when generic method returns nothing:
public static void castto<t, tresult>(this t arg, out tresult var) { typeconverter typeconverter = typedescriptor.getconverter(typeof(t)); bool? converter = typeconverter?.canconvertto(typeof(tresult)); if (converter != null && converter == true) var = (tresult)typeconverter.convertto(arg, typeof(tresult)); else var = default(tresult); }
and use so:
string s = "1"; int i; s.castto(out i);
it know both base type , output type without having explicitely name them.
Comments
Post a Comment