代码之家  ›  专栏  ›  技术社区  ›  Fernando Torres

如何使方法的返回对象泛型?

  •  2
  • Fernando Torres  · 技术社区  · 9 年前

    我需要执行以下代码,但新的T()不起作用。上面写着 “无法创建变量类型T的实例,因为它没有新的()约束。”

    public static T MapToBaseDropDown2<T>(this GenericDropDownData dd) where T : BaseDropDown
    {
        return new T() //FAILS
        {
            Id = dd.Id,
            Description = dd.Description
        };
    }
    

    BaseDropDown是3个子对象的基类,这些子对象是使用EntityFramework(代码优先)映射的实体,因此最好尽量保持简单。

    public class BaseDropDown
    {
        public int Id { get; set; }
        public string Description { get; set; }
    }
    
    4 回复  |  直到 9 年前
        1
  •  2
  •   MakePeaceGreatAgain    9 年前

    使命感 new T() 假设每种类型 有 BaseDropDown

    class BaseDropDown
    {
        public BaseDropDown() { /* see parameterless-constructor exists */ }
    }
    abstract class MyClass : BaseDropDown
    {
        public MyClass() { ... }
    }
    

    现在你可以使用 new -约束到 抽象类:

    public static T MapToBaseDropDown2<T>(this GenericDropDownData dd) where T : BaseDropDown, new()
    

    该约束只允许继承的类 和

        2
  •  2
  •   Fernando Torres    9 年前

    这也有效,只需添加 new()

    public static T MapToBaseDropDown3<T>(this GenericDropDownData dd) where T : BaseDropDown, new()
    {
        return new T()
        {
            Id = dd.Id,
            Description = dd.Description
        };
    }
    
        3
  •  1
  •   Stephen Wilson    9 年前

    BaseDropDown 班级需要 new()

    public class BaseDropDown<T> where T : SomeClass, new()
    {
    }
    

    这个 新建() 约束必须始终最后应用。看见 here

        4
  •  -1
  •   Fernando Torres    9 年前

    public static T MapToBaseDropDown2<T>(this GenericDropDownData dd) where T : BaseDropDown
    {
        T entityDd = (T)Activator.CreateInstance(typeof(T));
        entityDd.Id = dd.Id;
        entityDd.Description = dd.Description;
        return entityDd;
    }