我循环遍历 EF 的 ObjectStateEntry,这样我就可以访问 enrty.Entity,我正在对 poco 类进行一些静态验证,我还想进行业务规则验证,所以我创建了一个库来执行此操作,现在我有这行代码需要一个类型,例如 Customer..
MyEntityValidator<needtypehere> ev = new MyEntityValidator<needtyehere>(new EntityValidator());
所以我在传递类型时遇到了问题,我提到了“needtypehere”。我尝试了 entry.Entity.GetType() 但没有工作。同样,这是方法的签名
GetErrors(this ObjectStateEntry entry)
最佳答案
要从 Type
实例调用泛型,您必须使用:
Type closedType = typeof(MyEntityValidator<>)
.MakeGenericType(entry.Entity.GetType());
object obj = Activator.CreateInstance(closedType);
这很……尴尬——因为您随后需要通过反射做很多额外的工作。或者,您可以调用执行代码的通用方法:
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);
关于c# - 将类型传递给泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4274132/