重载泛型构造函数中的类型参数或约束

时间:2020-04-28 12:34:34

标签: c# generics constructor-overloading

我有一个通用类,我想要多个构造函数。在这些构造函数之一中,我想将type参数提供给重载的构造函数。这可能吗?

所以说我有这个。

public class Collection<T>
{
    public Collection(IEnumerable<T> collection, Func<T, T, int> distanceCalculation)
    {

    }
}

这将起作用。现在,我可以使用类似的实例

var collection = new Collection<int>(new List<int>(), (a, b) => a - b);

但是我现在想使使用Collection类更容易,所以我创建了一个类似IComparable的接口,以在类本身中定义距离计算逻辑:

public interface IDistanceCalculable
{
    int CalculateDistance(object other);
}

我以为我可以为Collection创建另一个构造函数,但这不能编译:

public Collection(IEnumerable<IDistanceCalculable> collection) : this<IDistanceCalculable>(collection, (a, b) => a.CalculateDistance(b))
{

}

public Collection(IEnumerable<T> collection) where T : IDistanceCalculable : this(collection, (a, b) => a.CalculateDistance(b))
{

}

因为我不能给要调用的基本构造函数提供类型参数,也不能在构造函数上指定其他约束。有什么办法可以做这样的事情吗?

我确实发现我可以使用静态方法来实现相同的目的,但是这感觉比新的构造方法更简洁的代码

public static Collection<V> From<V>(IEnumerable<V> collection) where V : IDistanceCalculable
{
    return new Collection<V>(collection, (a, b) => a.CalculateDistance(b));
}

0 个答案:

没有答案