Specifying constructor constraint for Generic Parameter [duplicate]

戏子无情 提交于 2019-12-01 16:43:47

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.

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.

You can't constrain generic type constructors in this way (only to require a parameterless constructor), but you could take a delegate to do the construction:

public static IList<T> ConvertTo<A, T>(this IEnumerable<A> list, Func<A, T> constructionFunc)
{
    return list.Select(constructionFunc).ToList();
}

And use it like this:

var IList<T> converted = someSequence.ConvertTo(a => new T(a));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!