jeudi 29 juin 2017

Creating static behavior that can be overridden in derived classes in C#

Here's the specific situation: I have a base abstract class Effect that contains some behavior that is shared amongst all types of effects. Then I have several derived class that inherit from Effect.

I want to have something like

public static virtual Effect CreateEffect(GameObject obj)
{
    if (!IsCreateable()) {
        return;
    }

    //Otherwise create the effect
}

public static virtual bool IsCreateable()
{
    //Some generic logic common amongst all Effects
}

And then in derived classes some of them require some extra custom logic

public static override bool IsCreateable()
{
     if (custom logic) {
         return false;
     }

     return base.IsCreateable()
}

Obviously this isn't possible because c# doesn't support static virtual function. I would like a way to share this static code amongst the classes without having to rewrite code. I can't have it as an instance method because in this case the code is being used to decide whether to create an instance in the first place.

In general, how do you have functions that is type-level (doesn't require an instance) with default behavior that can be overridden or modified in C#?

Assume this behavior is something separate from the constructor (for example in Unity3D you can't use a constructor to instantiate Monobehaviors).

Aucun commentaire:

Enregistrer un commentaire