c# - 比类更易访问的方法

标签 c# java

在密封类中使用比类本身具有更大可访问性的方法是否合理。 当然只是不考虑后面的重构...

例子

class SomeClass
{
    public void SomeMethod()
    {
        ...
    }
}

最佳答案

(我的回答仅适用于 C#)

当然有用!

原因 1:

访问修饰符不能全部按顺序排列。

您认为 protectedinternal 更易于访问还是更差?

原因 2:

覆盖基类方法和实现接口(interface):

internal sealed class MyClass
{
    public override string ToString()
    {
        return "How would you do this without public methods?";
    }
}

现在通过将 MyClass 转换为 Object,该方法可以暴露在程序集之外。

在实现 IEnumerator 时经常使用这种模式。通常真正的类(class)是私有(private)的(甚至不是内部的)。

原因 3:

访问私有(private)嵌套类:

public class A
{
    public string TellMeWhy()
    {
        return B.TheReason;
    }

    sealed private class B
    {
        internal static string TheReason = 
            "How would you access any of these members " +
            "if they all have to be private?";
    }
}

关于c# - 比类更易访问的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6043390/

相关文章:

c# - GetEnvironmentVariable ("TEMP") 没有波浪号 (~)

c# - 没有给出与 'firstName' 所需的形参 'Person.Person(string, string)' 相对应的参数

c# - 生成的 WEB API 帮助区域文档不显示响应正文格式/示例

c# - 是什么让 WCF 测试客户端出现在 WCF > WCF 服务应用程序而不是 ASP.NET Web 应用程序项目中?

c# - .NET 核心 2.2 : Validate [required] properties only when object is not null

java - 是否存在任何可视化(或至少记录)iBatis 映射的技术?

java - SimpleDateFormat 函数 parse(String s) 给出了错误的日期

java - 是否可以从堆转储中的 hprof 转储/线程查看线程

java - Effective Java Item 9,CaseInsensitiveString 示例是否正确?

java - 为什么类中的静态变量有时为空?