【问题标题】:Creating Generic class object using CreateInstance使用 CreateInstance 创建通用类对象
【发布时间】: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


【解决方案1】:

你确定你的Employee 实现了ITest?? 如果它在没有ITest 的情况下在 GenericController 上工作并且它显示 violates constraint,那么,结论是你传递的类型没有实现 ITest

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 2010-10-31
    相关资源
    最近更新 更多