c# - 如何使方法的返回对象通用?

标签 c# .net generics return-type

我需要做类似下面代码的事情,但是 new T() 不起作用。它说 “无法创建变量类型 T 的实例,因为它没有 new() 约束。”

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; }
}

最佳答案

调用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()

该约束将仅允许继承 BaseDropDown 的类使用无参数构造函数进行实例化。

关于c# - 如何使方法的返回对象通用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45370549/

相关文章:

c# - NUnit 3 重试测试n次

java - 嵌套的 Java 集合泛型

c# - JsonSerializer c# 在尝试反序列化对象时返回空结构

c# - 在布局充气机中获取 “an object reference is required to access non-static member”

c# - windows phone 8中如何监听scrollviewer的滚动事件?

c# - Azure函数输出API调用第三方服务

c# - 在 EF 6 中自动生成时间戳(代码优先): conversion of a datetime2 data type to a datetime data is an out-of-range value

c# - Entity Framework 6 : ignore property on basetype for all derived types

java - 具有泛型方法参数、返回类型和接口(interface)的工厂

c# - 使用泛型获取随机数据