c# – GetOriginalTypeParameterType throws未将对象引用设置为对象异常的实例

参考: How can a dynamic be used as a generic?
public void CheckEntity(int entityId,string entityType = null)
{
 dynamic AnyObject = Activator.CreateInstance("Assembly","Assembly.Models.DbModels." + entityType).Unwrap();
 CheckWithInference(AnyObject,entityId);
}

private static void CheckWithInference<T>(T ignored,int entityId) where T : class
{
 Check<T>(entityId);
}

private static void Check<T>(int entityId) where T : class
{
 using (var gr = new GenericRepository<T>())
 {
 }
}

这与CheckEntity(16,“容器”)进入;第一行运行后,AnyObject在使用调试器检查时变为空白Assembly.Models.DbModels.Container.如果var AnyType = AnyObject.GetType();使用,然后AnyType显示为Assembly.Models.DbModels.Container.但是,当调用CheckWithInference(AnyObject,entityId)时;被抛出异常.

> outer:对象引用未设置为对象的实例.
> inner:Microsoft.CSharp.RuntimeBinder.SymbolTable.GetoriginalTypeParameterType(Type t)10

在这里做了一个自包含的例子 – 但它运行没有错误:(

注意,这是在asp.net mvc 3 c#

HomeController.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace InferenceExample.Controllers
{
public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View();
    }

    public void CheckEntity(int entityId,string entityType = null)
    {
        dynamic AnyObject = Activator.CreateInstance("InferenceExample","InferenceExample.Models." + entityType).Unwrap();
        CheckWithInference(AnyObject,entityId);
    }

    private static void CheckWithInference<T>(T ignored,int entityId) where T : class
    {
        Check<T>(entityId);
    }

    private static void Check<T>(int entityId) where T : class
    {
        var repo = new List<T>();
    }

}
}

Example.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace InferenceExample.Models
{
public class Example
{
    public int ExampleId { get; set; }
    public string Name { get; set; }
}
}

Index.cshtml

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

@Html.ActionLink("Start","CheckEntity",new { entityId = 16,entityType = "Example" })

我很茫然.为什么会得到这个例外?我无法轻易复制它.我不确定该示例还包含哪些内容,因为这是实际代码中的所有内容.

真正令人困惑的部分是在应用程序中,当发生此异常时,操作失败.但是,在重新访问页面并再次尝试时,不会抛出任何异常.

解决方法

正如在C#聊天室中所讨论的,这里的解决方案是完全绕过动态并使用反射来调用泛型方法. Dynamic有一些很好的功能,但有时会造成比它值得更多的麻烦,特别是当它可以在运行时获取Type对象时.
var modelType = Type.GetType("InferenceExample.Models." + entityType + ",InferenceExample");

var checkMethod = typeof(HomeController).getmethod("CheckWithInference",BindingFlags.NonPublic | BindingFlags.Static);
checkMethod.MakeGenericmethod(modelType).Invoke(null,new object[] { entityId });

乐意效劳 :)

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...