Статические дополнительные методы [дубликат]

Попробуйте что-то вроде этого:

@Unroll
class JobSpec extends Specification {
    def "spec"() {
        when:
        GroovySpy(StatusObj, global: true)
        def job = new Job(id: "ID")
        def param = "test"
        1 * StatusObj.withTransaction(_) >> { Closure action ->
            action.call()
        }
        1 * StatusObj.findByJobIdAndParam(job.id, param) >> status

        then:
        job.isStale(param) == isStale

        where:
        status | isStale
        0      | false
        1      | true
        2      | true
    }
}

Здесь action - ваш status = StatusObj.findByJobIdAndParam(getId(), param) из Job класса. Как это работает, можно найти в разделах Вычисление возвращаемых значений и Выполнение побочных эффектов в документации Спока. Также обратите внимание, что я сделал Job.getId() работой, добавив поле id в класс Job. Я не уверен, как это реализовано в вашем коде

157
задан Community 23 May 2017 в 12:02
поделиться

5 ответов

In short, no, you can't.

Long answer, extension methods are just syntactic sugar. IE:

If you have an extension method on string let's say:

public static string SomeStringExtension(this string s)
{
   //whatever..
}

When you then call it:

myString.SomeStringExtension();

The compiler just turns it into:

ExtensionClass.SomeStringExtension(myString);

So as you can see, there's no way to do that for static methods.

And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:

Bool.Parse(..)

vs.

Helper.ParseBool(..);

Doesn't really bring much to the table...

148
ответ дан 23 November 2019 в 21:47
поделиться

specifically I want to overload Boolean.Parse to allow an int argument.

Would an extension for int work?

public static bool ToBoolean(this int source){
    //do it
    //return it
}

Then you can call it like this:

int x = 1;

bool y=x.ToBoolean();
76
ответ дан 23 November 2019 в 21:47
поделиться

It doesn't look like you can. See here for a discussion on it

I would very much like to be proven wrong though.

4
ответ дан 23 November 2019 в 21:47
поделиться

No, but you could have something like:

bool b;
b = b.YourExtensionMethod();
-11
ответ дан 23 November 2019 в 21:47
поделиться

You could add an extension method to int

public static class IntExtensions
{
    public static bool Parse(this int value)
    {
        if (value == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public static bool? Parse2(this int value)
    {
        if (value == 0)
        {
            return true;
        }
        if (value == 1)
        {
            return false;
        }
        return null;
    }
}

used like this

        bool bool1 = 0.Parse();
        bool bool2 = 1.Parse();

        bool? bool3 = 0.Parse2();
        bool? bool4 = 1.Parse2();
        bool? bool5 = 3.Parse2();
-2
ответ дан 23 November 2019 в 21:47
поделиться
Другие вопросы по тегам:

Похожие вопросы: