2010-07-11 87 views
1

当有唯一的代码是一个类你会如何编写其添加公众默认类,像这样清洁代码哪个版本正确?

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 
     { 
+1

HW2中的硬件是否代表作业? :) – 2010-07-11 14:46:02

+0

是的,它只是试图让它正确 – 2010-07-11 14:47:10

回答

6

一般情况下,每个类都应该有自己的文件。

Main应在Program.cs中

有usecases这里可以用内部类,见​​Using Inner classes in C#

+0

非常感谢你 – 2010-07-11 14:49:06

+0

@Micheal:外部存在(CLR)需要能够找到你的默认类来启动你的程序。因此,由于需要外部可访问性,它应该是一个公共类。 – 2010-07-11 14:52:59

+1

@Vitor,即使你没有在它前面写任何东西,具有“Main”的类也会被自动声明为public。你甚至不能宣布它是私人的。 – 2010-07-11 14:57:19

0
//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 
    } 
} 
+1

您不需要在具有'Main'的类中添加public修饰符,实际上它总是公开的,您不能将其设置为private/protected。 – 2010-07-11 15:13:20

+0

我更喜欢显式指定访问修饰符。 – 2010-07-11 17:29:14