Domanda

I've created a simple math-related extension method, and would like to add it as a definition to the UnityEngine.Mathf struct, simply so I can call it from the same type as I would other math functions. Is this possible?

My method:

public static int ZeroIfLess(this Mathf math, int num)
{
    if(num < 0)
    {
        return 0;
    }
    else
    {
        return num;
    }
}

I also tried adding it as an extension method to System.Math, but that didn't work either, due to it being static.

Ideally, I'd like it in UnityEngine.Mathf, but System.Math would also be appropriate.

È stato utile?

Soluzione

you can't extend static classes (unless they are marked as partial), you need to create your own

or just extend int itself

public static int ZeroIfLess(this int num)
{
    if(num < 0)
    {
        return 0;
    }
    else
    {
        return num;
    }
}

or just use a one-liner in-place instead:

Math.Max(num, 0)

Altri suggerimenti

Extension methods are declared as static, but look like instance methods. Thus, you cannot use this mechanism to add something that looks like a static method.

Your example would require an instance of Mathf (or Math) to be passed, which is not possible with classes that cannot be instantiated.

I'm afraid what you want is not possible in C#.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top