c# - Return class derived from generic constraint from a task -
i have created generic task interface
public interface icalcloadertask { task<t> execute<t>(basetaskparameters taskparams, cancellationtoken cancellationtoken) t : calcloadertaskresult; } and class derived calcloadertaskresult
public class copynmstoreresult : calcloadertaskresult { public string nmstoreresultsfilepath { get; set; } } in implementation of icalcloaderclass, cannot figure out way return results class
public async task<t> execute<t>(basetaskparameters taskparams, cancellationtoken cancellationtoken) t : calcloadertaskresult { var copyfiletaskparams = (copyfilestaskparameters)taskparams; var globalnmstoreresultsfilepath = string.format("{0}\\whateverthefilenameis.xls", copyfiletaskparams.globalsharefolderpath); var localnmstoreresultsfilepath = string.format("{0}\\whateverthefilenameis.xls", copyfiletaskparams.globalsharefolderpath); await fileutility.copyfileasync(globalnmstoreresultsfilepath, localnmstoreresultsfilepath, cancellationtoken); var result = new copynmstoreresult { nmstoreresultsfilepath = globalnmstoreresultsfilepath }; return result; //cannot implicitly convert type } how return thisresult? or pattern incorrect? re-using type of pattern different return types derived calcloadertaskresult. calcloadertaskresult abstract
since implementation returns object of same type, formulate interface differently
public interface icalcloadertask<t> t : calcloadertaskresult { task<t> execute(basetaskparameters taskparams, cancellationtoken cancellationtoken) } i.e. type (interface) generic instead of method.
and let implementation implement concrete type
public class myimplementation : icalcloadertask<copynmstoreresult> { public async task<copynmstoreresult> execute(basetaskparameters taskparams, cancellationtoken cancellationtoken) { ... var result = new copynmstoreresult { nmstoreresultsfilepath = globalnmstoreresultsfilepath }; return result; } } because caller cannot choose type of return value anyway.
it technically possible let the generic type parameter open
public class myimplementation<t> : icalcloadertask<t> t ... but since return type of method hard-coded, there no advantage in doing so.
note: possible let method return different types. adding generic type constraint new allows create object new t(). constraint new means type t must have default constructor.
t mymethod<t>() t : mybase, new { return new t(); }
Comments
Post a Comment