C#与Java中的访问修饰符最佳实践 [英] Access modifier best practice in C# vs Java

查看:130
本文介绍了C#与Java中的访问修饰符最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,OOD中的经验法则是尽可能减少对给定对象的所有成员的访问权限。

I understand that the rule of thumb in OOD is to minimize access to all members of a given object as best as can be reasonably accomplished.

C#和Java似乎都实现了同一组访问修饰符;然而,令我困惑一段时间的东西现在是为什么Java类似乎主要被声明为公共,而C#类似乎主要被声明为默认。 这些语言是否有一些微妙的强加这些差异,还是仅仅是约定或什么?

我发现自己经常使用我的C#代码(我习惯性地将大多数课程公开,除了试图取悦编译器的内部类,匿名类和其他类的窄范围和有用性)但是我想知道我是否可能遗漏了一些重要的东西。

I find myself frequently going through my C# code (I habitually make most classes public, excepting inner classes, anonymous classes, and other classes of narrow scope and usefulness) in an attempt to please the compiler, however I wonder if I may be missing something important.

推荐答案

Java的范围 C#的范围略有不同。

这在 C#来自Java Developer's Perspective 的相同但不同:访问修饰符。这个文件现在有点过时了,但仍然是最相关的。

This is talked about briefly in C# From a Java Developer's Perspective's The Same, But Different: Access Modifiers. This document is slightly dated now, but is still mostly relevant.

该列表有两个错误:


  1. C#的 internal 相当于Java的默认范围(这是它自己的范围)。

  2. C#的 internal protected 相当于Java的 protected

  1. C#'s internal is equivalent to Java's default scope (which is its own scope).
  2. C#'s internal protected is equivalent to Java's protected.

此外,上述文档未提及类的默认访问修饰符,仅适用于方法和属性/变量。

Additionally, the above document doesn't mention what the default access modifiers are for classes, only for methods and properties/variables.

供参考,默认c#中的类的范围是内部的。 Java是其通常的默认范围,如前所述。

For reference, the default scope for classes in c# is internal. Java's is its usual default scope, as described earlier.

这篇关于C#与Java中的访问修饰符最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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