c# - Passing Run time object types in side List<T> -
object obj = new customer(); type ty = obj.gettype(); validator<ty> cusvalidator = valfactory.createvalidator<ty>(); getting error here
is possible?
yes is. not compile-time type checking. runtime type ty not valid compile-time type argument. can done reflection, using makegenerictype method without safety of compile time check:
object obj = new customer(); type ty = obj.gettype(); methodinfo validatorfactory = valfactory.gettype() .getmethod("createvalidator") .makegenerictype(ty); var cusvalidator = validatorfactory.invoke(valfactory, null); but cannot type validator<ty> -- have use var or dynamic. aware type object:
// true: cusvalidator.gettype() == typeof(object) you may introduce non-generic validator interface allow invocation of methods on cusvalidator insert base class of customer (and on) classes validate it. can't cast validator<ty>.
Comments
Post a Comment