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

发布于 2024-10-16 11:56:32 字数 664 浏览 0 评论 0原文

我正在使用特定于任务的 .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();

所以有人有想法吗?感谢您的帮助!

问候内姆

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.

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!

Regards Nem

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

铁轨上的流浪者 2024-10-23 11:56:32

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

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

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

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"
 }
盛夏尉蓝 2024-10-23 11:56:32

现在,我看到的唯一“错误”是:

T result = 0;

您可以将其更改为:

T result = default(T);

在值类型的情况下,这将为零,因此它是安全的。

然而,当您到达列出的“...”部分时,您会发现这很困难。基本类型(intdouble 等)没有实现可用于计算数学的方法。这是一个Connect 上的长时间投票请求,顺便说一句。

虽然有解决办法,但它们让生活变得非常困难。与 C++ 中的模板不同,C# 的泛型实际上不支持任意类型的类型安全数学运算。

Right now, the only "error" I'd see is this:

T result = 0;

You could change that to:

T result = default(T);

In the case of value types, this will be zero, so it would be safe.

However, you're going to find that this is difficult when you get to the "..." section you've listed. The basic types (int, double, etc) don't implement a method you can use to compute your math. This is a long time, very highly voted request on Connect, btw.

While there are workarounds, they make life very difficult. Unlike templates in C++, C#'s generics really don't support type safe mathematical operations on arbitrary types.

葬花如无物 2024-10-23 11:56:32

您是否研究过“装饰器”...

显示装饰器模式的示例

装饰器允许您可以创建一个具有自己的属性和方法的类,而无需从某个特定类直接派生。然后,您可以将其“应用”到几乎任何其他对象。然后您可以应用您的额外方法或您尝试使用的属性。

这个示例是一个简单的快速查找,显示了这样一个通过构建“选项”将自身附加到“汽车”的示例......

Have you looked into "Decorators"...

Sample showing Decorator patterns

A decorator allows you to create a class with its own properties and methods without doing a direct derivation from one specific class. Then, you can "apply" it to virtually ANY other object. Then you can apply use your extra methods, or properties you are trying to work with.

This sample was a simple quick find showing such an example attaching itself to "cars" by building "options"...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文