最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

解析C#編程的通用結(jié)構(gòu)和程序書寫格式規(guī)范

 更新時(shí)間:2016年01月28日 14:23:09   投稿:goldensun  
這篇文章主要介紹了C#編程的通用結(jié)構(gòu)和程序書寫格式規(guī)范,這里我們根據(jù)C#語(yǔ)言的開發(fā)方微軟給出的約定來(lái)作為編寫樣式參照,需要的朋友可以參考下

C# 程序的通用結(jié)構(gòu)
C# 程序可由一個(gè)或多個(gè)文件組成。每個(gè)文件都可以包含零個(gè)或零個(gè)以上的命名空間。一個(gè)命名空間除了可包含其他命名空間外,還可包含類、結(jié)構(gòu)、接口、枚舉、委托等類型。以下是 C# 程序的主干,它包含所有這些元素。

// A skeleton of a C# program 
using System;
namespace YourNamespace
{
  class YourClass
  {
  }

  struct YourStruct
  {
  }

  interface IYourInterface 
  {
  }

  delegate int YourDelegate();

  enum YourEnum 
  {
  }

  namespace YourNestedNamespace
  {
    struct YourStruct 
    {
    }
  }

  class YourMainClass
  {
    static void Main(string[] args) 
    {
      //Your program starts here...
    }
  }
}

C# 編碼約定

C# 語(yǔ)言規(guī)范 未定義編碼標(biāo)準(zhǔn)。但是,Microsoft 根據(jù)本主題中的準(zhǔn)則來(lái)開發(fā)樣本和文檔。
編碼約定可實(shí)現(xiàn)以下目的:

  • 它們?yōu)榇a創(chuàng)建一致的外觀,以確保讀取器專注于內(nèi)容而非布局。
  • 它們使得讀取器可以通過(guò)基于之前的經(jīng)驗(yàn)進(jìn)行的假設(shè)更快地理解代碼。
  • 它們便于復(fù)制、更改和維護(hù)代碼。
  • 它們展示 C# 最佳做法。

命名約定

在不包括 using 指令的短示例中,使用命名空間限定。如果你知道命名空間默認(rèn)導(dǎo)入項(xiàng)目中,則不必完全限定來(lái)自該命名空間的名稱。如果對(duì)于單行來(lái)說(shuō)過(guò)長(zhǎng),則可以在點(diǎn) (.) 后中斷限定名稱,如下面的示例所示。

var currentPerformanceCounterCategory = new System.Diagnostics.
  PerformanceCounterCategory();

你不必更改通過(guò)使用 Visual Studio 設(shè)計(jì)器工具創(chuàng)建的對(duì)象的名稱以使它們適合其他準(zhǔn)則。
布局約定
好的布局利用格式設(shè)置來(lái)強(qiáng)調(diào)代碼的結(jié)構(gòu)并使代碼更便于閱讀。Microsoft 示例和樣本符合以下約定:

  • 使用默認(rèn)的代碼編輯器設(shè)置(智能縮進(jìn)、4 字符縮進(jìn)、制表符保存為空格)。有關(guān)詳細(xì)信息,請(qǐng)參閱選項(xiàng)、文本編輯器、C#、格式設(shè)置。
  • 每行只寫一條語(yǔ)句。
  • 每行只寫一個(gè)聲明。
  • 如果連續(xù)行未自動(dòng)縮進(jìn),請(qǐng)將它們縮進(jìn)一個(gè)制表符位(四個(gè)空格)。
  • 在方法定義與屬性定義之間添加至少一個(gè)空白行。

使用括號(hào)突出表達(dá)式中的子句,如下面的代碼所示。

if ((val1 > val2) && (val1 > val3))
{
  // Take appropriate action.
}

注釋約定
將注釋放在單獨(dú)的行上,而非代碼行的末尾。
以大寫字母開始注釋文本。
以句點(diǎn)結(jié)束注釋文本。
在注釋分隔符 (//) 與注釋文本之間插入一個(gè)空格,如下面的示例所示。

// The following declaration creates a query. It does not run
// the query.

不要在注釋周圍創(chuàng)建格式化的星號(hào)塊。
語(yǔ)言準(zhǔn)則
以下各節(jié)介紹 C# 遵循以準(zhǔn)備代碼示例和樣本的做法。
String 數(shù)據(jù)類型
使用 + 運(yùn)算符來(lái)連接短字符串,如下面的代碼所示。

string displayName = nameList[n].LastName + ", " + nameList[n].FirstName;
若要在循環(huán)中追加字符串,尤其是在使用大量文本時(shí),請(qǐng)使用 StringBuilder 對(duì)象。

var phrase = "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala";
var manyPhrases = new StringBuilder();
for (var i = 0; i < 10000; i++)
{
  manyPhrases.Append(phrase);
}
//Console.WriteLine("tra" + manyPhrases);

隱式類型的局部變量
當(dāng)變量類型明顯來(lái)自賦值的右側(cè)時(shí),或者當(dāng)精度類型不重要時(shí),請(qǐng)對(duì)本地變量進(jìn)行隱式類型化。

// 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());

當(dāng)類型并非明顯來(lái)自賦值的右側(cè)時(shí),請(qǐng)勿使用 var。

// When the type of a variable is not clear from the context, use an
// explicit type.
int var4 = ExampleClass.ResultSoFar();

請(qǐng)勿依靠變量名稱來(lái)指定變量的類型。它可能不正確。

// Naming the following variable inputInt is misleading. 
// It is a string.
var inputInt = Console.ReadLine();
Console.WriteLine(inputInt);

避免使用 var 來(lái)代替 dynamic。
使用隱式類型化來(lái)確定 for 和 foreach 循環(huán)中循環(huán)變量的類型。
下面的示例在 for 語(yǔ)句中使用隱式類型化。

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

下面的示例在 foreach 語(yǔ)句中使用隱式類型化。

foreach (var ch in laugh)
{
  if (ch == 'h')
    Console.Write("H");
  else
    Console.Write(ch);
}
Console.WriteLine();

無(wú)符號(hào)數(shù)據(jù)類型
通常,使用 int 而非無(wú)符號(hào)類型。 int 的使用在整個(gè) C# 中都很常見,并且當(dāng)你使用 int 時(shí),更易于與其他庫(kù)交互。
數(shù)組
當(dāng)在聲明行上初始化數(shù)組時(shí),請(qǐng)使用簡(jiǎn)潔的語(yǔ)法。

// 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.

委托
使用簡(jiǎn)潔的語(yǔ)法來(lái)創(chuàng)建委托類型的實(shí)例。

 // 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);
}


 // 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);

異常處理中的 try-catch 和 using 語(yǔ)句
對(duì)大多數(shù)異常處理使用 try-catch 語(yǔ)句。

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;
  }
}

通過(guò)使用 C# using 語(yǔ)句簡(jiǎn)化你的代碼。如果你具有 try-finally 語(yǔ)句(該語(yǔ)句中 finally 塊的唯一代碼是對(duì) Dispose 方法的調(diào)用),請(qǐng)使用 using 語(yǔ)句代替。

// 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;
}

&& 和 || 運(yùn)算符
若要通過(guò)跳過(guò)必要的比較來(lái)避免異常和提高性能,請(qǐng)?jiān)趫?zhí)行比較時(shí)使用 && 來(lái)代替 &,使用 || 來(lái)代替 | ,如下面的示例所示。

Console.Write("Enter a dividend: ");
var dividend = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter a divisor: ");
var divisor = Convert.ToInt32(Console.ReadLine());

// If the divisor is 0, the second clause in the following condition
// causes a run-time error. The && operator short circuits when the
// first expression is false. That is, it does not evaluate the
// second expression. The & operator evaluates both, and causes 
// a run-time error when divisor is 0.
if ((divisor != 0) && (dividend / divisor > 0))
{
  Console.WriteLine("Quotient: {0}", dividend / divisor);
}
else
{
  Console.WriteLine("Attempted division by 0 ends up here.");
}

New 運(yùn)算符
隱式類型化時(shí),請(qǐng)使用對(duì)象實(shí)例化的簡(jiǎn)潔形式,如下面的聲明所示。

var instance1 = new ExampleClass();

上一行等同于下面的聲明。

ExampleClass instance2 = new ExampleClass();

使用對(duì)象初始值設(shè)定項(xiàng)來(lái)簡(jiǎn)化對(duì)象創(chuàng)建。

// 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;

事件處理
如果你正定義一個(gè)稍后不需要?jiǎng)h除的事件處理程序,請(qǐng)使用 lambda 表達(dá)式。

 public Form2()
{
  // You can use a lambda expression to define an event handler.
  this.Click += (s, e) =>
    {
      MessageBox.Show(
        ((MouseEventArgs)e).Location.ToString());
    };
}


 // 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());
}


靜態(tài)成員
通過(guò)使用類名稱調(diào)用靜態(tài)成員:ClassName.StaticMember。這種做法通過(guò)明確靜態(tài)訪問使代碼更易于閱讀。請(qǐng)勿使用派生類的名稱限定基類中定義的靜態(tài)成員。編譯該代碼時(shí),代碼可讀性具有誤導(dǎo)性,如果向派生類添加具有相同名稱的靜態(tài)成員,代碼可能會(huì)被破壞。
LINQ 查詢
對(duì)查詢變量使用有意義的名稱。下面的示例為位于西雅圖的客戶使用 seattleCustomers。

var seattleCustomers = from cust in customers
            where cust.City == "Seattle"
            select cust.Name;

使用別名確保匿名類型的屬性名稱都使用 Pascal 大小寫格式正確大寫。

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

如果結(jié)果中的屬性名稱模棱兩可,請(qǐng)對(duì)屬性重命名。例如,如果你的查詢返回客戶名稱和分銷商 ID,而不是在結(jié)果中將它們保留為 Name 和 ID,請(qǐng)對(duì)它們進(jìn)行重命名以明確 Name 是客戶的名稱,ID 是分銷商的 ID。

var localDistributors2 =
  from cust in customers
  join dist in distributors on cust.City equals dist.City
  select new { CustomerName = cust.Name, DistributorID = dist.ID };

在查詢變量和范圍變量的聲明中使用隱式類型化。

var seattleCustomers = from cust in customers
            where cust.City == "Seattle"
            select cust.Name;

對(duì)齊 from 子句下的查詢子句,如上面的示例所示。
在其他查詢子句之前使用 where 子句,以確保后面的查詢子句作用于經(jīng)過(guò)減少和篩選的數(shù)據(jù)集。

var seattleCustomers2 = from cust in customers
            where cust.City == "Seattle"
            orderby cust.Name
            select cust;

使用多行 from 子句代替 join 子句以訪問內(nèi)部集合。例如,Student 對(duì)象的集合可能包含測(cè)驗(yàn)分?jǐn)?shù)的集合。當(dāng)執(zhí)行以下查詢時(shí),它返回高于 90 的分?jǐn)?shù),并返回得到該分?jǐn)?shù)的學(xué)生的姓氏。

// Use a compound from to access the inner sequence within each element.
var scoreQuery = from student in students
         from score in student.Scores
         where score > 90
         select new { Last = student.LastName, score };

相關(guān)文章

最新評(píng)論

蒙山县| 霸州市| 静海县| 木兰县| 泌阳县| 金平| 德惠市| 苍溪县| 时尚| 秦皇岛市| 大英县| 买车| 上饶市| 贵阳市| 九寨沟县| 疏附县| 革吉县| 扬州市| 右玉县| 门头沟区| 威宁| 比如县| 陕西省| 横峰县| 四平市| 辽中县| 湄潭县| 封丘县| 宝清县| 陕西省| 郁南县| 沈阳市| 通江县| 长宁区| 乌兰县| 黄平县| 牙克石市| 丹寨县| 同心县| 克山县| 蒙城县|