C# how to force generic argument to be type -
i have generic method. want generic method limit 1 type. problem derived type not allowed - not want this. example codes:
public static t generate<t>(t input) t : operation // allows binaryoperation - not want { //... } how request?
problem derived type not allowed
there no way enforce constraint, without checking @ runtime. doing violation of liskov substitution principle, states type should allow pass in derived type without restriction.
if must enforce this, work runtime check, like:
public static t generate<t>(t input) t : operation // allows binaryoperation - not want { // checks see if "operation" (and not derived type) if (input.gettype() != typeof(operation)) { // handle bad case here... } // alternatively, if want not allow "binaryoperation", can do: if (input binaryoperation) { // handle "bad" case of binaryoperation passed in here... } } note that, in case, there's no reason make generic, same code work as:
public static operation generate(operation input) { // ...
Comments
Post a Comment