C# .cs 文件名和类名需要匹配吗?
在 Java 中,文件名必须是该 java 文件中定义的公共类名。 C#有类似的要求吗?我可以有一个 A.cs 文件,里面只定义了一个公共 B 类吗?谢谢,
In Java the file name must be the public class name defined in that java file. Does C# has similar requirement? can I have a A.cs file which only defines a public Class B inside? thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,没有类似的要求。
是的,你可以这样做。
然而,这被认为是不好的做法。
如果您这样做,Microsoft StyleCop 会警告您,但一切都会正常编译。
No, there is no similar requirement.
Yes, you can do this.
It is considered bad practice, however.
Microsoft StyleCop will warn you if you do this, but everything will compile fine.
不,不要求文件名与文件中定义的单个公共类匹配。事实上,包含文件的名称和文件中定义的任何类之间没有必要存在关系。这一声明隐含的是,甚至可以在同一个封闭文件中定义多个类(即使有多个类是公共的,与 Java 不同)。此外,可以使用
partial< 跨多个文件定义一个类。 /code>
关键字。
然而,最佳实践是为每个文件定义一个类,并为该文件指定与所定义的类(或结构体等)相同的名称。
No, there is not a requirement that the filename matches a single public class being defined in the file. In fact, it is not necessary to have a relationship between the name of the containing file and any classes that are defined in the file. Implicit in this statement is that it is even possible to define more than one class in the same enclosing file (even if there are multiple classes that are public, unlike Java). Moreover, it is possible to define a class across multiple files using the
partial
keyword.Best practice, however, is to define one class per file and to give the file the same name as the class (or struct, etc.) being defined.
不,在 C# 中,您不必将类命名为与文件相同的名称。
类似地,您可以在文件中包含多个
public
类。 Java 只让你拥有一个。这对于在一个文件中定义一些公共枚举很有帮助。几个小班。
然而,将太多内容放入一个文件中是一种不好的做法。
No, in C# you don't have to name your class the same as your file.
Along a similar line, you can have multiple
public
classes in on file. Java only lets you have one.This can be helpful for defining a few public enums in one file. Of a few small classes.
It is bad practice however to throw too much into one file.
可以有一个包含公共类
B
的文件A.cs
,但这被认为是不好的做法。It is possible to have a file
A.cs
that contains public classB
but it is considered to be bad practice.