
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 }); 乐意效劳 :)
总结以上是内存溢出为你收集整理的c# – GetOriginalTypeParameterType throws未将对象引用设置为对象异常的实例全部内容,希望文章能够帮你解决c# – GetOriginalTypeParameterType throws未将对象引用设置为对象异常的实例所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)