如何使方法的返回对象通用? [英] How do I make the return OBJECT of a method generic?

查看:56
本文介绍了如何使方法的返回对象通用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要像下面的代码那样做,但是新的T()不起作用.它说无法创建变量类型T的实例,因为它没有new()约束."

I need to do somthing like below code, but new T() does not work. It says "Cannot create an instance of variable type T because it does not have a new() constraint."

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

BaseDropDown是3个子对象的基类,它们是用EntityFramework映射的实体(代码优先),因此最好使其尽可能简单.

BaseDropDown is the base class for 3 childs that are entities mapped with EntityFramework (code first), so it may be better keep it as simple as possible.

由于我尝试了某些实现,现在它不是抽象的,但是如果可能的话,它将是抽象的.

Now it is not abstract due to some implementations that I tried, but if possible it will be.

public class BaseDropDown
{
    public int Id { get; set; }
    public string Description { get; set; }
}

推荐答案

这也有效,只需将 new()约束直接添加到T(而不是添加到BaseDropDown)

This also works, just adding the new() constraint directly to T (not to BaseDropDown)

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

这篇关于如何使方法的返回对象通用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆