GetOriginalTypeParameterType throws Referência de objeto não definida para uma instância de uma exceção de objeto
Referência:Como uma dinâmica pode ser usada como genérica?
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>())
{
}
}
Isso entra comCheckEntity(16,"Container");
. Depois que a primeira linha é executada,AnyObject
torna-se um espaço em brancoAssembly.Models.DbModels.Container
quando inspecionado com o depurador. E sevar AnyType = AnyObject.GetType();
é usado, entãoAnyType
mostra comoAssembly.Models.DbModels.Container
. No entanto, quando a chamada paraCheckWithInference(AnyObject, entityId);
é feita uma exceção é lançada.
Eu fiz um exemplo auto-contido aqui - mas é executado sem erro :(
Note, isso é no 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" })
Eu estou perdido. Por que estou recebendo essa exceção? Não consegui reproduzi-lo facilmente. Não tenho certeza do que mais incluir no exemplo, pois isso é tudo o que o código real tem nele.
A parte realmente confusa é que, no aplicativo, quando essa exceção ocorre, a ação falha. No entanto, ao revisitar a página e tentar uma segunda vez, não há exceção.