为通用参数指定构造函数约束 [英] Specifying constructor constraint for Generic Parameter

查看:103
本文介绍了为通用参数指定构造函数约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象集合,我将其作为参数传递以创建另一种类型的对象(一对一)。我在很多地方都这样做(基本上是从数据对象转换为业务对象)。我想写一个通用的扩展方法来完成这个。但是我被卡住了,因为我不知道如何指定约束条件,即业务对象具有以数据对象为参数的构造函数。以下是我的函数的代码:

I have a collection of objects which I pass as parameter to create objects of another type (one for one). I am doing this in many places (basically converting from data objects to business objects). I want to write a generic extension method to accomplish this. But I am stuck because I don't know how I can specify constraint that business object has a constructor taking data object as parameter. Following is code of my function:

public static IList<T> ConvertTo<A,T>(this IEnumerable<A> list) 
                    where T : new(A)/*THIS IS PROBLEM PART*/
{
    var ret = new List<T>();

    foreach (var item in list)
    {
        ret.Add(new T(item));
    }
    return ret;
}


推荐答案

允许在C#中。你可以有一个 new()约束来强制这个类有一个默认的构造函数,但这是.NET支持的唯一与构造函数相关的约束。

Unfortunately, this isn't allowed in C#. You can have a new() constraint that forces the type to have a default constructor, but that is the only constructor related constraint supported by .NET.

您最好的选择可能是定义一个您可以使用的界面,并限制界面。您可以使用初始化样式方法来获取A对象,然后调用它,而不是尝试在构造中设置对象。

Your best option is probably to define an interface you can use, and constrain to the interface. Instead of trying to set the object at construction, you can have an "Initialize" style method that takes the "A" object, and call that.

这篇关于为通用参数指定构造函数约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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