我正在使用特定于任务的 .NET 平台,该平台是预编译的,而不是开源的。
对于某些任务,我需要扩展此类,但不是通过继承它。我只是想添加一个方法。
首先,我想向您展示一个虚拟代码现有类:
public class Matrix<T> where T : new() {
...
public T values[,];
...
}
我想通过以下方式扩展这个类:
public static class MatrixExtension {
public static T getCalcResult<T>(this Matrix<T> mat) {
T result = 0;
...
return result;
}
}
我从许多谷歌链接中得到了这个语法,所以不知道它是否正确。编译器告诉我没有错误,但最终它不起作用。最后我想通过以下方式调用这个函数:
Matrix<int> m = new Matrix<int>();
...
int aNumber = m.getCalcResult();
那么有人有想法吗?感谢您的帮助!
问候内姆
您需要在扩展方法上添加相同类型的参数约束。
这是我对编译和运行示例的最接近重建的尝试,没有任何错误:
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"
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)