开发者

How do I write an extension method for a generic type with constraints on type parameters?

开发者 https://www.devze.com 2023-02-09 18:16 出处:网络
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.

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 id开发者_StackOverflow社区ea? Thank you for your help!

Regards Nem


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消