截至
C# 11 / .NET 7,可以通过在包含必要参数的静态抽象工厂创建方法上应用约束,然后在所有相关类型中实现该接口来实现此目标。
例如,首先定义以下接口:
public interface ICreatable<TArgument, TResult>
{
public abstract static TResult Create(TArgument arg);
}
然后,在您的
Method<T>
中,如果您希望
T
具有一个接受2D浮点数组的静态工厂方法,可以按照以下方式约束它:
public class A
{
public static void Method<T> (T a) where T : ICreatable<float[,], T>
{
var t = T.Create(new [,] { { 1f, 2f }, {3f, 4f} });
}
}
当然,你传入
Method<T>
的任何类型都需要实现
ICreatable<float[,], T>
,例如如下所示:
public partial class Matrix2DFloat : ICreatable<float[,], Matrix2DFloat>
{
readonly float[,] array;
public Matrix2DFloat(float[,] array) => this.array = array ?? throw new ArgumentNullException(nameof(array));
public static Matrix2DFloat Create(float[,] arg) => new Matrix2DFloat(arg);
}
演示fiddle
here。
new(float, double)
,new(string)
等。 - SliverNinja - MSFT