嗚嗚喔學習筆記

搜尋此網誌

2016年8月28日 星期日

C# Coding Standards ( Coding 標準 )

參考 MSDN 的coding style 以下是整理最 基礎 , 常使用 的部分

基礎規則:
  • 使用大駱駝 Pascal( 如 : "VirtualDesign" )及小駱駝Camel( 如 : "virtualDesign" )
    • 不要使用分隔符號( 例如底線 "_" 或連字號 "-" )來做命名 ( EX: (X) User_Name_Api_Path )
  • 可讀性優先於簡潔性( CanScrollHorizontally 優於 ScrollableX ),並參考常用的命名( HorizontalAlignment 優於 AlignmentHorizontal )。
  • 避免使用匈牙利命名法( 如 : "strName", )
    • 不要使用型態前致詞( ex: (x)strName ,)
    • Bool 例外 "Can" , Is 或 "Has"( EX: (O)bool isPlay )
    • 使用後致詞
      • System.EventArgs :  AppleEventArgs    
      • System.Exception :  WtfException
      • System.Attribute : LoginAttribute
      • Instance (Field): CubeInstance
  • 正確的使用縮寫 (沒事不要用縮寫)
    • 兩字皆為大寫( 如 : "IO" , "DB" , system.IO  )
    • 三個字以上 ( 如 : "Xml" )
物件命名規則:
  • Interface : 前面+I ( EX: Car : ICar )
  • Generic (泛型) : 前面+T , K ( EX:  class List <TKey , TValue > )
  • Field :
    • public : 大寫開頭 ( EX : public string UserName )大駱駝
    • private :  ( EX: private string _userName )_小駱駝
    • private Const -> WTFUSER ;
  • Local Variable : 小寫開頭 ( EX: string userName )小駱駝
  • Const (static readonly) Variable 全大寫_ (EX: WTF_PATH = “@C:\” )
  • Parameter : 小寫開頭 ( EX: userName )
  • var 不可以寫在成員 public private

2016年8月26日 星期五

工廠模式&策略模式 差別

工廠模式-> 創建物件 ->
車工廠 -> 跑車 , 國產車
通過車工廠可以直接拿取跑車
呼叫者不需研究跑車如何組裝 , 國產車如何組裝
優點: 新增老爺車時 實例化只需關注介面( 剎車 起跑 換檔 ..)
調用車子 ->不須關心車子如何組裝 如何實體化
缺點: 更改介面時 所有車子都要改


策略模式-> 封裝方法 ->
皮卡丘.上() 皮卡丘.下() 皮卡丘.左() 皮卡丘.右()
小火龍.上() 小火龍.下() 小火龍.左() 小火龍.右()


到真心鎮的策略->可能是 上右右上右下 -> 也可能是 上下下右右右上

優點:抽換策略 , 只關心策略演算

2016年7月21日 星期四

C#-Delegates & Events

程式碼:
using System;
class Program
{
    static void Main()
    {
        var ball = new Ball();
        var patcher = new Pitcher(ball);

        ball.OnBallInPlay(new BallEventArgs(100, 200));
        
        Console.ReadLine();

    }
    class BallEventArgs : EventArgs
    {        // BallEventArgs class 繼承 EventArgs
        public int Trajectory { get; private set; }
        public int Distance { get; private set; }
        public BallEventArgs(int Trajectory, int Distance)
        {
            this.Trajectory = Trajectory;
            this.Distance = Distance;
        }
    }
    class Ball
    {
        private EventHandler _ballInPlay;

        // Ball class
        public event EventHandler BallInPlay {
            add
            {
                _ballInPlay += value;
            }
            remove
            {
                _ballInPlay -= value;
            }
        } 

        public void OnBallInPlay(BallEventArgs e)
        {
            _ballInPlay?.Invoke(this, e);// 觸發 BallInPlay 事件 
        }
    }
    class Pitcher
    {   // Pitcher class
        public Pitcher(Ball ball)
        {
            ball.BallInPlay += new EventHandler(ball_BallInPlay);   // 訂閱 BallInPlay 事件
        }
        void ball_BallInPlay(object sender, EventArgs e)
        {   // BallInPlay 事件處理方法
            if (e is BallEventArgs)
            {        // 判斷物件是否為 BallEventArgs 實體
                BallEventArgs ballEventArgs = e as BallEventArgs;  // 將物件由 EventArgs 轉型 BallEventArgs
                if ((ballEventArgs.Distance < 95) && (ballEventArgs.Trajectory < 60))
                    Console.WriteLine("  CatchBall();");
                else
                    Console.WriteLine("  CoverFirstBase();");
            }
        }
    }
}

結果:

2016年7月18日 星期一

C#-Extension Method-擴充方法

能夠擴充.NET 原有的方法 "方便好用"
關鍵字在 "this"
程式碼:
using System;

public static class ExtensionMethods
{
    //這是我自訂的方法 關鍵字 this Int32 指定要被擴充的型別 
    //如果需要擴充String 就改成 this String 
    public static String ToStringAddTag(this Int32 value,string tag)
    {
        return tag + value.ToString();
    }
}

class Program
{
    static void Main()
    {
        Int32 num = 100;

        //現在 Int32 多出了 ToStringAddTag 這個方法了~
        String TagInt2Str = num.ToStringAddTag("TAG");

        Console.WriteLine("TagInt2Str  ->  {0}", TagInt2Str);

        Console.ReadLine();
    }
}
結果:

C#-[泛型&List]

List<T> -> 可以放任何型態 -> List<int> -> List<String> ->List<Point>(自訂義Class也行的)
程式碼:
using System;
using System.Collections.Generic;

class TestClass
{
    static void Main()
    {
        var list = new List<Point>();

        list.Add(new Point { x=1, y=1 });
        list.Add(new Point { x=1, y=2 });
        foreach (var item in list)
        {
            Console.WriteLine("Point->({0},{1})", item.x, item.y);
        }

        Console.ReadLine();
    }

    struct Point
    {
        public int x;
        public int y;
    }
}
結果:

2016年7月17日 星期日

C#-Delegate

Delegate

簡單的說就是能夠 "傳遞方法"

程式碼:
using System;
namespace SimpleEvent
{
    //建照標準函式 型態參數一樣才能註冊
    public delegate string DelegatePrint(string Name);

    class Suzanne
    {
        //必須和Delegate型態參數一模一樣
        public static string print01(string formDelegateStr )
        {
            Console.WriteLine("print 01 " + formDelegateStr);
            return "Done";
        }
        //必須和Delegate型態參數一模一樣
        public static string print02(string formDelegateStr)
        {
            Console.WriteLine("print 02 " + formDelegateStr );
            return "Done";
        }

        //必須和Delegate型態參數一模一樣
        public static string print03(string formDelegateStr)
        {
            Console.WriteLine("print 03 " + formDelegateStr);
            return "Done";
        }

        public static void Main()
        {
            //用print01來註冊 delegatePrint
            DelegatePrint delegatePrint = new DelegatePrint( print01 );

            //用print02來註冊 delegatePrint
            delegatePrint += print02;

            //這時候 delegatePrint => print01() , print02()
            Console.WriteLine(delegatePrint("FromDelegateStr"));

            //再增加一個 print03 //總共有 print01 , print02 , print03 三個函式了~
            delegatePrint += print03;

            //delegatePrint() => print01() , print02() , print03() 
            //因為剛剛註冊了三個函式
            Console.WriteLine(delegatePrint("FromDelegateStr"));

            Console.ReadLine();
        }
    }
}
結果: 

2016年7月15日 星期五

C#-Dictionary

查表
using System;
using System.Collections;
using System.Collections.Generic;

/// <summary>
///     A simple indexer example.
/// </summary>
class ConsolePrint
{

    static void Main(string[] args)
    {
        Dictionary<string, string> dctNewWay =
        new Dictionary<string, string>()
        {
            {"Key1", "AAAA"}, {"Key2", "BBBB"},
            {"Key3", "CCCC"}, {"Key4", "DDDD"}
        };

        dctNewWay.Add("Key5", "EEEE");

        String FindByKey = dctNewWay["Key1"]; 
        bool AnyKey = dctNewWay.ContainsKey("key1");
        Console.WriteLine("FindByKey = {0}", FindByKey);
        Console.ReadLine();
    }
}