简体   繁体   中英

How do I call static method for a generic type in a class?

interface TerminationCondition
{
    static bool IsSatisfied(some parameters);
}

Let's say some classes A and B implement this interface.

Some other class C has a generic type:

class C<termCondition> where termCondition : TerminationCondition

I need to call IsSatisfied from C accordingly, whether I have passed A or B for the generic type. For some reason it is not possible termCondition.IsSatisfied().

To summarize, the question is How do I call static method for a generic type in a class?

This is not possible.

In fact, you can't have static methods in an interface at all.

Since termCondition is required to be of type TerminationCondition , you could simple have IsSatisfied be an instance method of the classes that implement that interface. There's no need to have that method be static at all.

bool result = C<TerminationCondition>.IsSatisfied();

As @SLaks pointed out, you can't have static methods in an interface. Having them in a generic type tends to be awkward.

@Austin also makes a good point.

You can have static generic methods (normally in non-generic types); these have their uses.

public static bool IsSatisfied<T>(T condition)
    where T: TerminationCondition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM