我怎样写一个通用的类型与类型参数的约束扩展方法?类型、怎样写、参数、方法

2023-09-03 15:46:49 作者:忙着耍酷

我的工作与任务特定的.NET plattform,这是precompiled,而不是开源。 对于某些任务,我需要从它继承来继承这个类,但并非如此。我只是想添加一个方法。

I'm working with a task specific .NET plattform, which is precompiled and not OpenSource. For some tasks I need to extend this class, but not by inheriting from it. I simply want to add a method.

起初,我想告诉你一个虚拟的code存在的类:

At first I want to show you a dummycode existing class:

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

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

I want to extend this class in the following way:

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

我有这种语法许多谷歌的链接,以便不知道它是否是正确的。编译器告诉我没有错误,但最终这是行不通的。最后我想调用此函数以下列方式:

I've got this syntax from many google links so no idea whether it is correct. The compiler tells me no error, but in the end it doesn't work. In the end I want to call this function in the following way:

Matrix<int> m = new Matrix<int>();
...
int aNumber = m.getCalcResult();

因此​​,任何人有一个想法?谢谢您的帮助!

So anyone got an idea? Thank you for your help!

问候焾

推荐答案

您需要添加同一类型参数约束的扩展方法。

You need to add the same type parameter constraints on the extension method.

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

This is my attempt at the closest reconstruction of your example that compiles and runs, without any error:

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"
 }