How to use partial method in C# to extend existing implemetation

泪湿孤枕 提交于 2019-12-23 12:39:13

问题


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.



来源:https://stackoverflow.com/questions/32710975/how-to-use-partial-method-in-c-sharp-to-extend-existing-implemetation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!