c# 学习之一:编码约定

从今天开始我希望能够踏踏实实的把c#的每个知识点学习到并记录下来,以此来增长自己的基础知识。


任何语言在学习之前都应该了解和遵循它的编码规范来做,这样的好处有这几点:

  • 它们为代码创建一致的外观,以确保读取器专注于内容而非布局。

  • 它们使得读取器可以通过基于之前的经验进行的假设更快地理解代码。

  • 它们便于复制、更改和维护代码。

  • 它们展示 C# 最佳做法

c#的官方编码约定有很多更加详细的说法,这里是他的官方链接: 官方编码约定,这里我主要记录下平时我比较在意的一些点。


1:string 数据类型的使用

若要在循环中追加字符串,尤其是在使用大量文本时,请使用 StringBuilder 对象。

 
 
var phrase = "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala" ;
var manyPhrases = new StringBuilder();
for ( var i = 0; i < 10000; i++)
{
manyPhrases.Append(phrase);
}
 
2:隐式类型的局部变量

 
 
  • 当变量类型明显来自赋值的右侧时,或者当精度类型不重要时,请对本地变量进行隐式类型化

    C#
    // When the type of a variable is clear from the context, use var 
    // in the declaration.
    var var1 = "This is clearly a string.";
    var var2 = 27;
    var var3 = Convert.ToInt32(Console.ReadLine());
    
  • 当类型并非明显来自赋值的右侧时,请勿使用 var

    C#
    // When the type of a variable is not clear from the context, use an
    // explicit type.
    int var4 = ExampleClass.ResultSoFar();
    
  • 请勿依靠变量名称来指定变量的类型。它可能不正确。

    C#
    // Naming the following variable inputInt is misleading. 
    // It is a string.
    var inputInt = Console.ReadLine();
    Console.WriteLine(inputInt);
    
  • 避免使用 var 来代替 dynamic

  • 使用隐式类型化来确定 for 和 foreach 循环中循环变量的类型。

    下面的示例在 for 语句中使用隐式类型化。

    C#
    var syllable = "ha";
    var laugh = "";
    for (var i = 0; i < 10; i++)
    {
        laugh += syllable;
        Console.WriteLine(laugh);
    }
    

    下面的示例在 foreach 语句中使用隐式类型化。

    C#
    foreach (var ch in laugh)
    {
        if (ch == 'h')
            Console.Write("H");
        else
            Console.Write(ch);
    }
    Console.WriteLine();
3.使用简洁的语法
比如:
 
 
C#
// Preferred syntax. Note that you cannot use var here instead of string[].
string[] vowels1 = { "a", "e", "i", "o", "u" };


// If you use explicit instantiation, you can use var.
var vowels2 = new string[] { "a", "e", "i", "o", "u" };

// If you specify an array size, you must initialize the elements one at a time.
var vowels3 = new string[5];
vowels3[0] = "a";
vowels3[1] = "e";
// And so on.
C#
  // First, in class Program, define the delegate type and a method that  
// has a matching signature.

// Define the type.
public delegate void Del(string message);

// Define a method that has a matching signature.
public static void DelMethod(string str)
{
    Console.WriteLine("DelMethod argument: {0}", str);
}
C#
  // In the Main method, create an instance of Del.

// Preferred: Create an instance of Del by using condensed syntax.
Del exampleDel2 = DelMethod;

// The following declaration uses the full syntax.
Del exampleDel1 = new Del(DelMethod);







4.异常处理中的 try-catch 和 using 语句

  • 对大多数异常处理使用 try-catch 语句。

    C#
    static string GetValueFromArray(string[] array, int index)
    {
        try
        {
            return array[index];
        }
        catch (System.IndexOutOfRangeException ex)
        {
            Console.WriteLine("Index is out of range: {0}", index);
            throw;
        }
    }
    
  • 通过使用 C# using 语句简化你的代码。如果你具有 try-finally 语句(该语句中 finally 块的唯一代码是对 Dispose 方法的调用),请使用 using 语句代替。

    C#
    // This try-finally statement only calls Dispose in the finally block.
    Font font1 = new Font("Arial", 10.0f);
    try
    {
        byte charset = font1.GdiCharSet;
    }
    finally
    {
        if (font1 != null)
        {
            ((IDisposable)font1).Dispose();
        }
    }
    
    
    // You can do the same thing with a using statement.
    using (Font font2 = new Font("Arial", 10.0f))
    {
        byte charset = font2.GdiCharSet;
    }
5. 在创建对象的时候你可以试用初始值设定项来简化对象创建。

C#
// Object initializer.
var instance3 = new ExampleClass { Name = "Desktop", ID = 37414, 
    Location = "Redmond", Age = 2.3 };

// Default constructor and assignment statements.
var instance4 = new ExampleClass();
instance4.Name = "Desktop";
instance4.ID = 37414;
instance4.Location = "Redmond";
instance4.Age = 2.3;
6. 如果你正定义一个稍后不需要删除的事件处理程序,请使用 lambda 表达式。

C#
  public Form2()
{
    // You can use a lambda expression to define an event handler.
    this.Click += (s, e) =>
        {
            MessageBox.Show(
                ((MouseEventArgs)e).Location.ToString());
        };
}
C#
  // Using a lambda expression shortens the following traditional definition.
public Form1()
{
    this.Click += new EventHandler(Form1_Click);
}

void Form1_Click(object sender, EventArgs e)
{
    MessageBox.Show(((MouseEventArgs)e).Location.ToString());
}

ps:去学习一个东西就要真正了解,运用,熟练使用它,不能一知半解,含糊不清的过目了事。这是程序员的大忌 = =

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值