c# - Is it possible to define an extension method on a generic type and return another generic type without defining two generic types in <> -
this question has answer here:
is possible this:
public static t convertto<t>(this tinput input) {
and use:
item.converttype<newobject>()
or have this:
public static tresult converttype<tinput, tresult>(this tinput input) {
and use:
item.converttype<originalobject, newobject>()
it seems redundant have specify type extension method called on, missing something?
no, basically. there few tricks can do, if important enough.
you can like:
var dest = item.convert().to<something>();
via like:
static conversionstub<tinput> convert<tinput>(this tinput input) { return new conversionstub<tinput>(input); }
where:
struct conversionstub<t> { private readonly t input; public conversionstub(t input) { this.input = input; } public tresult to<tresult>() { /* code here */ } }
you can things dynamic
hooking operator path, cause boxing value-types; if convert
method returned dynamic
, dynamic
in question own provider, work.
but basically:
class conversionstub<t> : dynamicobject { private readonly t input; public conversionstub(t input){ this.input = input; } public override bool tryconvert(convertbinder binder, out object result) { if(/* can it*/ ) { result = // code here return true; } result = null; return false; } }
with:
static dynamic convert<tinput>(this tinput input) { return new conversionstub<tinput>(input); }
then:
sometype dest = item.convert();
should job.
Comments
Post a Comment