为什么GetGenericTypeDefinition失败? [英] Why does GetGenericTypeDefinition fail?

查看:129
本文介绍了为什么GetGenericTypeDefinition失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,当被我的存储库保存时,需要检查一个实体.我在保存时有一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆