如何使用分部方法在C#扩展现有的实现 [英] How to use partial method in C# to extend existing implemetation

查看:224
本文介绍了如何使用分部方法在C#扩展现有的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这将是巨大的,如果这是可行的。我是想实现我的方式是错误的想法?

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.

基本上正是的引用是说明:

分部方法使类设计人员提供的方法钩,
类似的事件处理程序,开发人员可以决定执行或
没有。如果开发商不提供一个实现,编译器
去除在编译时的签名。

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?

谢谢!

推荐答案

您可以用它调用私有方法的公共方法,但我不知道这是你想要的。这只是让你的代码的工作。

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.

这篇关于如何使用分部方法在C#扩展现有的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆