【发布时间】:2013-04-15 07:16:05
【问题描述】:
我有以下代码示例
public interface ITest
{
string abc { get; set; }
}
public class GenericController<T> : Controller where T : class, ITest, new()
{
public string abc { get; set; }
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
}
现在尝试使用以下代码创建对象给我错误 -
Type typeObject = typeof(Employee);
Type object1 = typeof(GenericController<>).MakeGenericType(typeObject);
controller = (IController)Activator.CreateInstance(object1);
给出的错误是
GenericArguments[0], 'MvcApplication2.Controllers.Employee', on 'MvcApplication2.Controllers.GenericController`1[T]' 违反了类型 'T' 的约束。
从 GenericController 类中删除 ITest 接口可以正常工作。我需要该接口,因此将控制器对象类型转换为接口我可以设置新创建对象的一些属性。
如何解决这个问题。
-拉杰什
【问题讨论】:
-
我找到了相同的解决方案。类应使用以下语句编写 class public class GenericController
: Controller, ITest where T : class, new() -Rajesh
标签: generics activator createinstance