VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > C#编程 >
  • C#教程之C#编码规范

本站最新发布   C#从入门到精通
试听地址  
https://www.xin3721.com/eschool/CSharpxin3721/

 

命名空间约定

如果没有使用using指令,项目也没有默认导入合适的命名空间,访问这些命名空间或者类型时,则需要“完全限定名称”。

复制代码
namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args) 
        {
            // 在这里System.Diagnostics是“完全限定名称”
            var traceSource = new System.Diagnostics.TraceSource("");
        }
    }
}
复制代码

如果使用了Using指令,则不需要“完全限定名称”。

复制代码
using System.Diagnostics;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {            
            var traceSource = new TraceSource("");
        }
    }  
}
复制代码

 

代码布局约定

  1. 不轻易更改编辑器的设置,通常使用默认的,特别是格式设置和制表符。
  2. 每行一条语句,每行一个声明。
    复制代码
    string[] strs = new string[] { "AA","BB","CC"};
    string str = "hello";
    int num = 4;
    if (num == 9)
    {
    
    }
    复制代码
  3. 一行写不完的语句,断行写则需要缩进一个制表符位,除了起头的第一行,后面无论再断多少行都是一个制表符位。
    string[] strs = new string[] { "AA","BB","CC"};            
    var query = strs.Where(x => x.Length == 2 && x.Contains("B")).
        Select(x => new { Name = x, Age = 8 });
  4. 属性和方法之间至少一个空行
    复制代码
    public int MyProperty { get; set; }
    public int MyProperty1 { get; set; }
    
    void Test()
    {
    
    }
    复制代码
  5. 使用括号突出表达式的字句。
    1
    2
    3
    4
    5
    6
    7
    8
    int val1 = 1;
    int val2 = 3;
    int val3 = 4;
     
    if ((val1 > val2) && (val1 > val3))
    {
        
    }

注释约定

单独的行,而非代码末尾;大写字母开头,断行换小写;句点结束注释文本;注释和文本之间留一个空格。

不要在注释周围创建格式化的星号块???没看懂。

下面放一段ILSpy源码

复制代码
/// <summary>
/// Sets the value of a dependency property on <paramref name="targetObject"/> using a markup extension.
/// </summary>
/// <remarks>This method does not support markup extensions like x:Static that depend on
/// having a XAML file as context.</remarks>
public static void SetValueToExtension(this DependencyObject targetObject, DependencyProperty property, MarkupExtension markupExtension)
{
    // This method was copied from ICSharpCode.Core.Presentation (with permission to switch license to X11)
    
    if (targetObject == null)
        throw new ArgumentNullException(nameof(targetObject));
    if (property == null)
        throw new ArgumentNullException(nameof(property));
    if (markupExtension == null)
        throw new ArgumentNullException(nameof(markupExtension));
    
    var serviceProvider = new SetValueToExtensionServiceProvider(targetObject, property);
    targetObject.SetValue(property, markupExtension.ProvideValue(serviceProvider));
}
复制代码

 

隐式类型var

当明显可以从赋值右侧推导左侧变量类型时,使用var。当精确的类型不太重要时,使用var。

var var1 = "This is clearly a string.";
var var2 = 27;
var var3 = Convert.ToInt32(Console.ReadLine());

右侧类型不明确时,则可以声明一个明确的类型。

复制代码
using System;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            string test = GetObject(2);
            int test1 = GetObject(1);
            decimal test2 = GetObject(3);
        }

        static dynamic GetObject(int x)
        {
            switch (x)
            {
                case 1:return 2;
                case 2:return "";
                default:return 8m;
            }
        }
    }   
}
复制代码

在for循环使用var,下面的i分别推导为int、decimal。

复制代码
for (var i = 0; i < 10000; i++)
{               
}

for(var i = 0m; i < 10m; i = i + 0.1m)
{
}
复制代码

在foreach中不建议使用var。

复制代码
DataTable dataTable = new DataTable();
// 枚举值:EnumerableRowCollection<DataRow>,可以推row为DataRow。
foreach (var row in dataTable.AsEnumerable())
{

}
// 虽然可以推,但声明明确的类型会让代码更加清晰,因为无法在枚举泛型类型里明显看出当前row的类型。
foreach (DataRow row in dataTable.AsEnumerable())
{

}
// 枚举值:DataRowCollection,不声明明确类型row则为object?,因此需要声明明确的类型。
foreach (DataRow row in dataTable.Rows)
{

}
复制代码

符号类型

使用时,符号类型优先于无符号类型。short、int、long。 ushort、uint、ulong。

数组

使用间接的语法声明数组

复制代码
// 这时候,无法从右侧推导变量类型。
string[] vowels1 = { "a", "e", "i", "o", "u" };

// 可以推导,左侧使用var
var vowels2 = new string[] { "a", "e", "i", "o", "u" };

var vowels3 = new string[2];
vowels3[0] = "a";
vowels3[1] = "e";
复制代码

委托

使用简短的语法为委托赋值。

复制代码
static void Main(string[] args)
{            
    Del exampleDel2 = DelMethod;
    var del3 = new Del(DelMethod);
}

public delegate void Del(string message);

public static void DelMethod(string str)
{
    Console.WriteLine("DelMethod argument: {0}", str);
}
复制代码

Using

如果使用try...finally...,且在finally只有释放资源的代码,考虑替换成using,using会自动调用Dispose方法。

复制代码
Font font1 = new Font("Arial", 10.0f);
try
{

}
finally
{
    font1.Dispose();
}

using(Font font=new Font("Arial", 10.0f))
{

}
复制代码

New运算符

能推导类型使用var,对象实例的构造函数没有参数则不必调用构造函数。

复制代码
// 不必使用new ExampleClass()
var instance3 = new ExampleClass
{
    Name = "Desktop",
    ID = 37414,
    Location = "Redmond",
    Age = 2.3
};

var instance4 = new ExampleClass();
instance4.Name = "Desktop";
instance4.ID = 37414;
instance4.Location = "Redmond";
instance4.Age = 2.3;
复制代码

事件处理

在事件比较简短、且只使用一次的情况下,可以考虑使用lambda表达式。

复制代码
public Form1()
{
    InitializeComponent();
    
    this.Click += (s, e) =>
    {
        MessageBox.Show(s.ToString());
    };
}
复制代码

 静态成员

 派生对象时,不建议添加和基类具有相同名称的静态成员。

复制代码
using System;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            ExampleClass2.Test();
        }      
    }

    class ExampleClass
    {
        public static void Test()
        {
            Console.WriteLine("调用ExampleClass Test");
        }
    }
    class ExampleClass2:ExampleClass
    {
        // 同名容易引起混乱,隐性覆盖了ExampleClass的Test方法。
        public static void Test()
        {
            Console.WriteLine("调用ExampleClass2 Test");
        }        
    }

    class ExampleClass3 : ExampleClass
    {
        // 使用new,说明有意覆盖。
        public new static void Test()
        {

        }
    }
}
复制代码

 Linq查询表达式

 匿名类型遵循Pascal大小写格式(与骆驼命名法类似,骆驼命名法是首字母小写,而Pascal帕斯卡命名法是首字母大写)。

复制代码
var localDistributors = from customer in customers
                        join distributor in distributors on customer.City equals distributor.City
                        select new
                        {
                            Customer = customer,
                            Distributor = distributor,
                            CustometorId = customer.ID
                        };
复制代码

在查询变量和范围变量的声明中使用隐式类型化,虽然查询变量没有明确标有var关键字,但确实隐式化了。

复制代码
using System;
using System.Linq;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            var customers = new System.Collections.Generic.List<Customer>();
            var distributors = new System.Collections.Generic.List<Distributor>();

            var localDistributors = from customer in customers
                                    join distributor in distributors on customer.City equals distributor.City
                                    select new
                                    {
                                        Customer = customer,
                                        Distributor = distributor,
                                        CustometorId = customer.ID
                                    };

        }
    }

    internal class Distributor
    {
        public object City { get; internal set; }
    }
    internal class Customer
    {
        public object City { get; internal set; }
        public object ID { get; internal set; }
    }
}
复制代码

对其from字句下面的查询语句。

复制代码
// 第一种:from语句不和声明变量同一行,则在下一行缩进一个制表符。

var localDistributors = 
    from customer in customers
    join distributor in distributors on customer.City equals distributor.City
    select new
    {
        Customer = customer,
        Distributor = distributor,
        CustometorId = customer.ID
    };  
          
// 第二种:from语句和声明变量同一行
var localDistributors = from customer in customers
                        join distributor in distributors on customer.City equals distributor.City
                        select new
                        {
                            Customer = customer,
                            Distributor = distributor,
                            CustometorId = customer.ID
                        };
复制代码

 

量变会引起质变。
相关教程