pass type to generic class
I am looping thru the ObjectStateEntry of EF so I can access enrty.Entity, I am doing some static validation on the poco classes and i want to also do business rule validation so i created a library to do that, now i have this line of code that expect a type excample Customer..
MyEntityValidator<needtypehere> ev = new MyEntityValidator<needtyehere>(new EntityValidator());
so I am having problem passing type where i mentiened 'needtypehere'. I tried entr开发者_运维技巧y.Entity.GetType() but not working . Again this is the signiture of the method
GetErrors(this ObjectStateEntry entry)
To invoke generics from a Type
instance, you would have to use:
Type closedType = typeof(MyEntityValidator<>)
.MakeGenericType(entry.Entity.GetType());
object obj = Activator.CreateInstance(closedType);
which is... awkward - as you then need to do lots of additional work with reflection. Alternatively, you can call into a generic method that does the code:
public static void InvokeGeneric<T>(...) {
MyEntityValidator<T> ev = new MyEntityValidator<T>(
new EntityValidator());
... etc; lots more code that uses ev
}
...
typeof(ContainingType).GetMethod("InvokeGeneric").MakeGenericMethod(
entry.Entity.GetType()).Invoke(null, args);
You can use MakeGenericType.
精彩评论