在 C# 中,所有声明都是内联的,每个成员声明中都包含“private”和“public”等访问说明符;在 C# 中,, public
, private
, protected
, 和internal
是成员的修饰符,就像static
在任何一种语言中一样:
public class MyClass
{
// ...
/// <summary>
/// The "///<summary>" convention is recognized by the IDE, which
/// uses the text to generate context help for the member.
///
/// As TyCobb notes below, method1 in correct C# idiom is more
/// likely to be a property than a method -- and the field "backing"
/// it would be given the same name, but with the first letter
/// lowercased and prefixed with an underscore.
/// </summary>
public int Property1
{
get { return _property1; }
set { _property1 = value; }
}
private int _property1 = 0;
private bool _flag1 = false;
// Regions are a convenience. They don't affect compilation.
#region Public Methods
/// <summary>
/// Do something arbitrary
/// </summary>
public void Method2()
{
}
#endregion Public Methods
}
私人是默认设置。请注意,您可以将初始化程序放在字段声明中。
没有直接等同于 .h/.cpp 的区别,尽管有诸如“部分类”之类的东西,其中给定类的一些成员在一个地方定义,而更多成员在其他地方定义。通常,如果一个类的某些成员由生成的代码定义,而其他成员则由手写代码定义。
将相关的东西(事件处理程序、访问 Web 服务的方法等)放在“区域”中是个好主意:
#region INotifyPropertyChanged Implementation
// ...declare methods which implement interface INotifyPropertyChanged
#endregion INotifyPropertyChanged Implementation
区域不仅仅是一种有趣的注释语法,但仅此而已:编译器需要#region/#endregion 对来匹配,Microsoft IDE 会在边缘为您提供一个小加号以折叠/展开区域。命名它们是可选的,但一个非常好的主意,以跟踪什么是什么。您可以嵌套它们,因此您需要跟踪它们。
我正在显式初始化所有内容,但那是 C# 确实将字段和变量隐式初始化为该类型的标准默认值:数字类型的默认值为 0,任何引用类型的默认值为null
等等。您可以为任何获取该值给定类型,带default(int)
,default(string)
等。