【问题标题】:Clean code which version is correct?清洁代码哪个版本是正确的?
【发布时间】:2010-07-11 14:42:45
【问题描述】:

当其中唯一的代码是一个类时,你将如何编码它,像这样将公共添加到默认类

namespace HW2_2_Spaceship
{
   public class Spaceship //added public to the default class 
    {
      static void Main(string[] args)
        {
        }

namespace HW2_1_Book
{
    class Book
    {
        static void Main(string[] args)
        {

        }
        public class Book // added a new class with in the default class
        {

【问题讨论】:

  • HW2中的HW代表作业吗? :)
  • 是的,只是想把它做好

标签: c#


【解决方案1】:

一般来说,每个类都应该有自己的文件。

Main 应该在 Program.cs 中

有些用例可以使用内部类,请参阅Using Inner classes in C#

【讨论】:

  • @Micheal:外部存在(CLR)需要能够找到您的默认类来启动您的程序。因此,由于需要外部可访问性,它应该是一个公共类。
  • @Vitor,具有Main 的类是自动声明为公共的,即使你没有在它前面写任何东西。您甚至不能将其声明为私有。
【解决方案2】:
//Program.cs, if u use visual studio then ensure you add
// the public access modifier yourself

namespace HW2_2_Spaceship
{
   public class Program
   {
      public static void Main(string[] args)
      {
        //Do something here
      }
   }
}

//Book.cs, add the public modifier to the class
namespace HW2_2_Spaceship
{
  public class Book
  {
   //add method and properties here
  }
}

【讨论】:

  • 你不需要在有Main的类上添加public修饰符,事实上它总是公共的,你不能将它设置为私有/受保护的。
  • 我更喜欢明确指定访问修饰符。
猜你喜欢
  • 1970-01-01
  • 2019-09-04
  • 2016-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-23
相关资源
最近更新 更多