c# - 如何在 C# 中使用部分方法来扩展现有实现

标签 c# oop partial-classes partial-methods

如果这能行得通就好了。我是否试图以错误的方式实现我的想法?

我想使用部分方法,以便能够扩展现有代码,并简单地插入/取出方法的实现。

基本上就是reference是说:

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.

我第一次尝试使用它如下:

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
        }
    }
}

程序.cs:

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

它是相同的命名空间,但作为引用状态部分方法是隐式私有(private)的。它不接受访问修饰符,我不能从我的类(class)中调用它。有没有办法按照我的意愿使用它?

谢谢!

最佳答案

您可以使用调用私有(private)方法的公共(public)方法,但我不确定这是否是您想要的。这只会使您的代码正常工作。

根据定义,部分方法是私有(private)的,因此在编译期间,如果该方法未实现,编译器无需遍历所有代码,找到对该方法的所有可能引用并将其删除。 这是一种设计选择,因为不一定需要实现部分方法,编译器只查看部分类实现,而不是查看所有代码。 如果您实现了一个调用分部方法的公共(public)方法,而分部方法未被实现,编译器仍将仅查看分部类文件和代码,即使您可以从代码中的任何位置访问该分部方法。

关于c# - 如何在 C# 中使用部分方法来扩展现有实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32710975/

相关文章:

c# - 使用部分类覆盖方法

c# - MVVMCross - BaseActivity 和 OnViewModelSet()

c# - 检测单击 TreeView 中的折叠按钮

c# - 如何在winforms中拥有一个ListBox的多种颜色的项目?

java - 有没有一种方法可以使方法在内部方法中返回?

java - 内部类的目的是什么

javascript - 当前项目告诉我需要查看 Javascript OOP,我应该吗?

java - 扩展自动生成的 JPA Controller (Netbeans 7.x)

c# - 从缩略图中检索原始图像

c# - 扩展类的问题和用方法覆盖