C#文件编写公约

Jun*_*mer 0 c# coding-style

如果我没有弄错,用C++编写类的传统方法如下(这只是一个说明性的例子):

MyClass.h

// MyClass.h

#ifndef MY_CLASS_H
#define MY_CLASS_H

class MyClass
{
public:
    MyClass();
    MyClass(int);
    void method1(int);
    int method2();

private:
    int field;
};

#endif
Run Code Online (Sandbox Code Playgroud)

MyClass.cpp

// MyClass.cpp 

#include "MyClass.h"

MyClass::MyClass()
{
    field = 0;
}

MyClass::MyClass(int n)
{
    field = n;
}

void MyClass::method1(int n)
{
    field = n;
}

int MyClass::method2()
{
    return field;
}
Run Code Online (Sandbox Code Playgroud)

main.cpp中

// main.cpp

#include <iostream>

#include "MyClass.h"

using namespace std;

int main()
{
    MyClass mc;

    mc.method1(2);
    cout << mc.method2();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这个项目的传统C#等价物是什么?此外,如果我在上面的例子中错误地描绘了传统上正确的C++,请修复它以帮助防止混淆未来的读者.

15e*_*153 5

在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
    }
Run Code Online (Sandbox Code Playgroud)

私有是默认的.请注意,您可以在字段声明上放置初始值设定项.

没有直接等同于.h/.cpp的区别,尽管存在诸如"部分类"之类的东西,其中给定类的一些成员在一个地方定义,而更多成员在其他地方定义.通常,如果一个类的某些成员由生成的代码定义,而其他成员在手写代码中定义,则完成.

在"区域"中将相关内容放在一起(事件处理程序,访问Web服务的方法,等等)是个好主意:

    #region INotifyPropertyChanged Implementation
    // ...declare methods which implement interface INotifyPropertyChanged
    #endregion INotifyPropertyChanged Implementation
Run Code Online (Sandbox Code Playgroud)

区域不仅仅是一个有趣的注释语法,而是更多:编译器需要#region/#endregion对匹配,并且Microsoft IDE将在折叠/扩展区域的边缘给你一点加号.命名它们是可选的,但是一个非常好的想法,以跟踪什么是什么.你可以嵌套它们,所以你需要跟踪.

我正在明确地初始化所有内容,但是C#会将字段和变量隐式初始化为类型的标准默认值:数字类型的默认值为零,任何引用类型的默认值为null,等等.您可以获取任何值的任何值给定的类型与default(int),default(string)