您使用过私有扩展方法吗?

发布于 2024-08-23 18:57:16 字数 59 浏览 4 评论 0原文

可以选择使用私有扩展方法有什么优势吗?我还没有发现它们有任何用处。如果 C# 根本不允许它们不是更好吗?

Is there any advantage of having the option of using private extension methods? I haven't found any use for them whatsoever. Wouldn't it be better if C# didn't allow them at all?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

箹锭⒈辈孓 2024-08-30 18:57:16

这有助于改进方法/类中的代码语法,但您不希望将该扩展方法提供的功能公开给代码库的其他区域。换句话说,作为常规私有静态辅助方法的替代方法

This is helpful for improving the syntax of code within a method/class, but you don't want to expose the functionality offered by that extension method to other areas of the codebase. In other words as an alternative for regular private static helper methods

紧拥背影 2024-08-30 18:57:16

考虑以下内容:

public class MyClass
{
    public void PerformAction(int i) { }
}

public static class MyExtensions
{
    public static void DoItWith10(this MyClass myClass)
    {
        myClass.DoIt(10);
    }

    public static void DoItWith20(this MyClass myClass)
    {
        myClass.DoIt(20);
    }

    private static void DoIt(this MyClass myClass, int i)
    {
        myClass.PerformAction(i);
    }
}

我意识到该示例在当前形式下没有多大意义,但我相信您可以欣赏私有扩展方法提供的可能性,即拥有使用私有扩展进行封装的公共扩展方法的能力或组成。

Consider the following:

public class MyClass
{
    public void PerformAction(int i) { }
}

public static class MyExtensions
{
    public static void DoItWith10(this MyClass myClass)
    {
        myClass.DoIt(10);
    }

    public static void DoItWith20(this MyClass myClass)
    {
        myClass.DoIt(20);
    }

    private static void DoIt(this MyClass myClass, int i)
    {
        myClass.PerformAction(i);
    }
}

I realize that the example does not make much sense in its current form, but I'm sure you can appreciate the possibilities that private extension methods provide, namely the ability to have public extension methods that use the private extension for encapsulation or composition.

爱本泡沫多脆弱 2024-08-30 18:57:16

我只是用谷歌搜索来调查,因为我怀疑它们有多大用处。然而,这对他们来说是一个很好的说明性应用程序:

http://odetocode.com/blogs/scott/archive/2009/10/05/private-extension-methods.aspx

I just Googled to investigate as I was doubtful that there was much use for them. This however is an excellent illustrative application for them:

http://odetocode.com/blogs/scott/archive/2009/10/05/private-extension-methods.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文