如何为类型参数约束的泛型类型编写扩展方法?

Chr*_*ner 15 .net c# generics methods

我正在使用特定于任务的.NET平台,它是预编译的而不是OpenSource.对于某些任务,我需要扩展此类,但不是通过继承它.我只是想添加一个方法.

首先,我想向您展示一个虚拟代码现有类:

public class Matrix<T> where T : new() {
    ...
    public T values[,];
    ...
}
Run Code Online (Sandbox Code Playgroud)

我想以下面的方式扩展这个类:

public static class MatrixExtension {
    public static T getCalcResult<T>(this Matrix<T> mat) {
        T result = 0;
        ...
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

我从许多谷歌链接获得这种语法,所以不知道它是否正确.编译器告诉我没有错误,但最终它不起作用.最后,我想以下列方式调用此函数:

Matrix<int> m = new Matrix<int>();
...
int aNumber = m.getCalcResult();
Run Code Online (Sandbox Code Playgroud)

所以任何人都有了主意?谢谢您的帮助!

问候内姆

Mar*_*ade 23

您需要在扩展方法上添加相同的类型参数约束.

这是我最近重建你编译和运行的例子的尝试,没有任何错误:

public class Matrix<T>  where T : new() {
     public T[,] values;
 }


 public static class MatrixExtension {
     public static T getCalcResult<T>(this Matrix<T> mat)  where T : new() {
         T result = new T();
         return result;
     }
 }

 class Program {
     static void Main(string[] args)  {
        Matrix<int> m = new Matrix<int>();
        int aNumber = m.getCalcResult();
        Console.WriteLine(aNumber); //outputs "0"
 }
Run Code Online (Sandbox Code Playgroud)

  • @Prokurors`where T:new()`约束意味着它需要一个默认构造函数(以便它可以被实例化).要仅指定引用类型,要使用的约束是"where T:class". (2认同)