How to use partial method in C# to extend existing

2019-06-26 08:09发布

问题:

It would be great if this would work. Am I trying to implement my idea in the wrong way?

I would like to use partial method, to be able to extend existing code, and simply plug in/out implementation of methods.

Basically exactly what the reference is stating:

Partial methods enable class designers to provide method hooks, similar to event handlers, that developers may decide to implement or not. If the developer does not supply an implementation, the compiler removes the signature at compile time.

My first try of using this is the following:

DefinitionsBase.cs:

namespace ABC {
    public partial class Definitions {
        // No implementation
        static partial void TestImplementaion();
    }
}

DefinitionsExt.cs:

namespace ABC {
    public partial class Definitions {
        static partial void TestImplementaion(){
            // Implementation is here
        }
    }
}

Program.cs:

namespace ABC {
    class Program {
        static void Main(string[] args) {
            Definitions.TestImplementaion();
        }
    }
}

It's same namespace, but as reference states partial methods are implicitly private. It doesn't accept access modifiers and I cannot call it from my class. Is there a way to use it as I intend to?

Thanks!

回答1:

You could use a public method that calls the private method, but I am not sure if this is what you want. This just makes your code work.

Partial methods are by definition private so as during compilation time, in case the method was not implemented, the compiler does not need to go through all of the code, find all possible references to the method, and remove them. This is a design choice since partial methods do not necessarily need to be implemented, the compiler only looks in the partial class implementation and not throughout all of the code. If you implement a public method that calls the partial method and the partial method was not implemented, the compiler will still only look in the partial class files and code, even though you have access to that partial method from anywhere in your code.