使用泛型时,如何定义泛型类型的静态实例化器?

When using generics, how do I define a static instantiator of the generic type?

我的目标(这样我就不会 运行 陷入 x-y 问题):

我正在尝试制作一个 Filter class,它适用于 T 泛型。由于过滤器适用于矢量操作,我想将对象转换为 Vector<double>,进行过滤,然后在请求数据后将其转换回 T

接口不能有静态方法

我制作了一个看起来应该像这样的界面。

public interface IFilterable {

    public Vector<double> ToVector();
   
    public static IFilterable FromVector(Vector<double> vec);
}

以便我可以在 Filter:

中使用它
public class Filter<T> where T: IFilterable {
    private Vector<double> _state;

    public T GetState() { 
        return T.FromVector(); 
    }

接口不能有静态方法,所以我正在寻找一种替代方法来提供这种行为,它仍然允许我使用 T 作为通用类型。

感谢@Fildor 提供接口解决方案:

public interface IFilterable<out T> where T: new() {

    abstract Vector<double> ToVector();

    T FromVector(Vector<double> vec);
}

Filter 可以这样使用:

public class Filter<T> where T : IFilterable<T>, new() {
    
    private Vector<double> _state;
    
    public T GetState() {
        return new T().FromVector(_state);
    }
}

其他解决方案包括使用抽象 class 而不是接口。