为什么GetGenericTypeDefinition失败? [英] Why does GetGenericTypeDefinition fail?
问题描述
我有一段代码,当被我的存储库保存时,需要检查一个实体.我在保存时有一个NHibernate拦截器来检查它,但是当我调用GetGenericTypeDefinition
函数时,代码失败并显示以下错误:
I have a piece of code which needs to check an entity when being saved by my Repository. I have an NHibernate interceptor on the save to check this but when I call the GetGenericTypeDefinition
function the code fails with the error:
[InvalidOperationException:由于对象的当前状态,操作无效. System.RuntimeType.GetGenericTypeDefinition()+7525641
[InvalidOperationException: Operation is not valid due to the current state of the object.] System.RuntimeType.GetGenericTypeDefinition() +7525641
代码是这样的:
protected override object PerformSaveOrUpdate(SaveOrUpdateEvent evt)
{
if (evt.Entity.GetType().GetGenericTypeDefinition() == typeof(IChild<>))
{
var parent = (evt.Entity as IChild<Entity>).Parent;
if (parent != null)
{
parent.UpdateCacheCounters();
evt.Session.Save(parent);
}
}
}
任何帮助将不胜感激.
推荐答案
Type type = evt.Entity.GetType();
if(
type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(IChild<>)
)
尝试一下.根据 http://msdn.microsoft.com/en-us/library/system. type.getgenerictypedefinition.aspx :
InvalidOperationException:当前 类型不是通用类型.那是, IsGenericType返回false.
InvalidOperationException: The current type is not a generic type. That is, IsGenericType returns false.
这篇关于为什么GetGenericTypeDefinition失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!