It could be a silly question, but please help to answer it. Currently I have an interface with 2 generic methods:
ValidationResult Validate<T>(T t);
IList<ValidationResult> ValidateList<T>(IEnumerable<T> entities);
What I want is if you want to validate an object, use Validate
method; if you want to validate an array of object, use ValidateList
method, pretty clear in mind and interface. But it seems user can also use Validate
method for a list of object without any compiler errors (of course!). Any there ways to restrict them to ValidateList
method? Thank you so much.
You can restrict a function to specific object types (and its derivatives) by doing something like this in the function declaration:
ValidationResult Validate<T>(T t) where T : ValidateBase, ValidateBaseOther
edit:
so in this case, the function will only take objects that are ValidateBase
or its derivatives, or ValidateBaseOther
or its derivatives. You can of course just use one if you want
ValidationResult Validate<T>(T t) where T : ValidateBase
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With