zoukankan      html  css  js  c++  java
  • C#编码规范

    记录 编码约定 学习过程。

    命名空间约定

    如果没有使用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. 使用括号突出表达式的字句。
      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 };
  • 相关阅读:
    开发一个App的成本是多少?
    自定义Drawable
    数据库服务软件类型和配置redis
    分库分表
    创建视图
    部署MYSQL高可用集群
    读写分离《二》
    读写分离和多实例
    部署mysql主从同步
    备份和恢复
  • 原文地址:https://www.cnblogs.com/bibi-feiniaoyuan/p/coding_conventions.html
Copyright © 2011-2022 走看看