顯示具有 C#語言入門 標籤的文章。 顯示所有文章
顯示具有 C#語言入門 標籤的文章。 顯示所有文章

2017年3月17日 星期五

[C#] 委派/泛型委派: Delegate vs. Action vs. Func vs. Lambda

自學筆記,幫助自己記憶,以利未來回想…

感謝老師的教學視頻:C#语言入门详解(特辑001) 



Delegate 己過時,進化成 Action、Func:

委派
delegate void MyDele();

泛型委派
delegate T MyDele<T>(T a, T b);

Action: 沒有返回值的委派,用於無回傳值的方法
Func: 有返回值的委派,用於有回傳值的方法


Lambda 表達式是
1. 匿名方法
2. Inline 方法
使用時機:程式中若有很多的細算法(e .g.加減乘除),臨時算一下用完就沒了,就可以使用Lambda。

※ Inline code:將Function(函式)的內容直接以inline 的方式寫在一般的程式碼之中,省去另外定義Function。MSDN: https://msdn.microsoft.com/zh-tw/library/bb397687.aspx


[建立概念]

委派是什麼?
1. 類似C++函式指標的概念。
2. 像是一個方法的封裝器,一個函式或是一組函式的封裝器。
 https://www.youtube.com/watch?v=g1EU9gnZKOg


模擬場景:
1. 小明最近學習情緒高漲,以前買的書已經滿足不了慾望,打算去買本(一個程序員的自我修養)。可是呢以前總是跑書廠買,太遠了扛不住,就去跑去附近書店去買,小明去給錢就弄了一本書回來,這個過程就是委託。
http://www.cnblogs.com/LipeiNet/p/4694225.html

2.  貓大叫一聲,所有的老鼠都開始逃跑,主人被驚醒。
程式要求:
(1). 要有聯動性,老鼠和主人的行為是被動的。
(2). 考慮可擴展性,貓的叫聲可能引發其他聯動效應。
http://www.programgo.com/article/24262282064/


[實作練習]

Delegate
1. 委派也是一種Class
2. 需要聲明
3. 參數類型要一致

Delegate(無返回值)

Example 1: 調用一個Function


    class Program {
        static void Main(string[] args) {
            MyDele dele1 = new MyDele(M1);
            dele1 += M1;   //多重委派,就是用委派變數+= 方法名稱
            dele1();
        }

        static void M1() {
            Console.WriteLine("M1 is called.");
        }
    }

    delegate void MyDele();

Example 2: 調用Class的Function


    class Program {
        static void Main(string[] args) {
            MyDele dele1 = new MyDele(M1);
            dele1 += new Student().SayHello;    //調用Class的Function
            dele1();

            Console.Read();
        }

        static void M1() {
            Console.WriteLine("M1 is called.");
        }
    }

    class Student {
        public void SayHello() {
            Console.WriteLine("Hello, I'm Riva.");
        }
    }

    delegate void MyDele();


Delegate(有返回值)

   class Program {
        static void Main(string[] args) {
            MyDele dele = new MyDele(Add);
            int result = dele(100, 200);
            Console.WriteLine(result);
        }

        static int Add(int x, int y) {
            return x + y;
        }
    }

    delegate int MyDele(int a, int b);


Generics Delegates (泛型委派):

    class Program {
        static void Main(string[] args) {
            MyDele<int> deleAdd = new MyDele<int>(Add);
            int addResult = deleAdd(100, 200);
            Console.WriteLine(addResult);

            MyDele<double> deleMul = new MyDele<double>(Mul);
            double mulResult = deleMul(3.0, 4.0);
            Console.WriteLine(mulResult);
        }

        static int Add(int x,int y) {
            return x = y;
        }

        static Double Mul(double x, double y) {
            return x * y;
        }
    }
    
    delegate T MyDele<T>(T a, T b);


Action (無參數)

    class Program {
        static void Main(string[] args) {
            Action action = new Action(M1);
            action();
        }

        static void M1() {
            Console.WriteLine("M1 is called.");
        }
    }

Action (有參數)

    class Program {
        static void Main(string[] args) {
            Action<string> action = new Action<string>(SayHello);
            action("Riva");
        }

        static void SayHello(string name) {
            Console.WriteLine("I'm {0}", name); //Console.WriteLine($"I'm {name}"); C# 6
        }
}


Action (多參數,不同類型)

    class Program {
        static void Main(string[] args) {
            var action = new Action<string, int>(SayHello);
            action("Riva", 3);
        }

        static void SayHello(string name, int round) {
            for (int i = 0; i < round; i++) {
                Console.WriteLine("Hello, {0}", name);
            }
        }
}



Func: 有回傳值

Func (Int類型)

    class Program {
        static void Main(string[] args) {
            Func<int, int, int> func = new Func<int, int, int>(Add);
            int res = func(100, 200);
            Console.WriteLine(res);
        }

        static int Add(int x, int y) {
            return x = y;
        }

Func (Double類型)

    class Program {
        static void Main(string[] args) {
            var func = new Func<double, double, double>(Mul);
            double result = func(3.0, 4.0);
            Console.WriteLine(result);
        }

        static Double Mul(double x, double y) {
            return x * y;
        }



Func + Lambda (泛型委派)

原始寫法:

    class Program {
        static void Main(string[] args) {
            Func<int, int, int> func = new Func<int, int, int>((int a, int b) => { return a + b; });
            int res = func(100,200);
            Console.WriteLine(res);

            func = new Func<int, int, int>((int x, int y) => { return x * y; });
            res = func(3,4);
            Console.WriteLine(res);
        }
    }

進一步簡化:(省略int)

    class Program {
        static void Main(string[] args) {
            Func<int, int, int> func = new Func<int, int, int>((a, b) => { return a + b; });
            int res = func(100, 200);
            Console.WriteLine(res);

            func = new Func<int, int, int>((x, y) => { return x * y; });
            res = func(3, 4);
            Console.WriteLine(res);
            Console.Read();
        }
    }


再簡化:(直接賦值給委派參數Lambda表達式) ★★★★★

    class Program {
        static void Main(string[] args) {
            Func<int, int, int> func = (a, b) => { return a + b; };
            int res = func(100, 200);
            Console.WriteLine(res);

            func = (x, y) => { return x * y; };
            res = func(3, 4);
            Console.WriteLine(res);
        }
    }



泛型方法+泛型的委派參數+泛型參數 ★★★★★
(泛型函式的參數為"Func類型的參數")

原始寫法:
namespace Combine {

    class Program {
        static void Main(string[] args) {
            DoSomeCalc<int>((int a, int b) => { return a * b; }, 100, 200);
            Console.Read();
        }

        static void DoSomeCalc<T>(Func<T,T,T> func, T x, T y) {
            T res= func(x, y);
            Console.WriteLine(res);
        }
    }

省略int
    class Program {
        static void Main(string[] args) {
            DoSomeCalc((a, b) => { return a * b; }, 100, 200);
        }

        static void DoSomeCalc<T>(Func<T, T, T> func, T x, T y) {
            T res = func(x, y);
            Console.WriteLine(res);
        }
    }



Ref:
1. C#语言入门详解(特辑001) ★★★★★
2. C#的委派與事件的使用:
3. [C#] 快速了解泛型委派:
4. 設計模式面試與筆試題剖析(二)
5. C#之Action和Func的用法
6. C# IN DEPTH

2016年11月14日 星期一

[C#] 使用 String.Join 串連陣列或字串

遇到就筆記一下…



IEnumerable yearList = Enumerable.Range(DateTime.Now.Year, 5);
Console.WriteLine(string.Join(" ", yearList));

2016 2017 2018 2019 2010


int[] arr = {1, 3, 5, 7, 9};
Console.WriteLine(string.Join(" - ", arr));

1 - 3 - 5 - 7 - 9


var numsFromOneToTen = string.Join(",", Enumerable.Range(1, 10));
Console.WriteLine(numsFromOneToTen);

1,2,3,4,5,6,7,8,9,10


//Join不同類型
object[] data = {string.Empty, "test", 123, .998, DateTime.Now};
string variousObjects = string.Join(" : ", data);
Console.WriteLine(variousObjects);

//Join不同類型
//var variousObjects = string.Join("-", "A", DateTime.Now, 3.14);
//Console.WriteLine(variousObjects);

: test : 123 : 0.998 : 11/14/2016 4:13:49 PM

Ref:
1. MSDN:
    https://msdn.microsoft.com/en-us/library/57a79xd0.aspx
2. C# 中奇妙的函数–7. String Split 和 Join
    http://www.cnblogs.com/multiplesoftware/archive/2011/09/17/2179380.html
3. [.NET]Enumerable.Range
    https://dotblogs.com.tw/rainmaker/2013/04/24/102208




C# 中奇妙的函数–7. String Split 和 Join

很多时候处理字符串数据,比如从文件中读取或者存入 - 我们可能需要加入分隔符(如CSV文件中的逗号),或使用一个分隔符来合并字符串序列。

很多人都知道使用split()的方法,但使用与其对应的Join()方法的人就没有那么多。今天,让我们看看它们的应用。

Split() – 根据分隔符切割字符串成几部分


分割符可以是以下几种形式中的一种:
  • 只有一个字符的数组:
    • 比方对于“A,B,C,D,E,F” 可以使用 ‘,’ 或者 new [] { ‘,’ }  
  • 有多个字符的数组:
    • 比方对于“A,B-C,D*E,F”使用 new [] { ‘,’ ‘-‘ ‘*’ } :
  • 只有一个字符串的数组:
    • 比方对于 “A=>B=>C=>D=>E=>F” new [] { “=>” } 
  • 有多个字符串的数组 :
    • 比方对于 “A=>B<=C=>D<=E=>F”使用 new [] { “=>”, “<=” }
让我们在实例中看看:

string testString = "James Hare,1001 Broadway Ave,St. Louis,MO,63101";
//传递的分割可以是一个数组
string[] results = testString.Split(new[] { ',' });
//或者在asp.net 4.0 下传递单独的一个char
results = testString.Split(',');
得到的结果如下
ScreenShot022 
 
对待同样的字符串,我们使用 ‘,’ 和 ‘ ‘ (空格):

string testString = "James Hare,1001 Broadway Ave,St. Louis,MO,63101";
//传递一个数组作为分割的标记
string[] results = testString.Split(new[] { ',', ' ' });
//或者在4.0 下可以直接这样传递
results = testString.Split(',', ' ');
得到下面的结果:
ScreenShot023

使用 string 作为分割符用法是基本一样的:
string testString = "James Hare,,1001 Broadway Ave,St. Louis,MO,63101";
string[] results = testString.Split(new[] { ",," }, StringSplitOptions.None);
结果:
ScreenShot024

注意在这里我们必须要提供一个 StringSplitOptions 的选择. 

这个枚举的类型有两个值:
  • StringSplitOptions.None: 包含返回的数组中的空数组元素.
  • StringSplitOptions.RemoveEmptyEntries:  省略返回的数组中的空数组元素.

最后, Split() 有一个形式是让你可以限制返回数组元素数量的. 在这种情况下,前面 n-1 的 元素基于你的条件生成,最后一个则是剩下的没有被分割的部分:
string testString = "James Hare,,1001 Broadway Ave,,,St. Louis,MO,63101";


//返回含有两个元素的数组.  

string[] results = testString.Split(new[] { ',' }, 2, StringSplitOptions.None);


for (int i = 0; i < results.Length; i++)
{
    Console.WriteLine("\tElement {0}: \"{1}\"", i, results[i]);
}
使用限制数量的结果是:
ScreenShot025

注意第二个元素还包含了’,’。

Join() – 串联对象数组的各个元素,其中在每个元素之间使用指定的分隔符

参数
separator
类型:System.String 要用作分隔符的字符串。
values
类型:System.Object[] 一个数组,其中包含要连接的元素。
返回值
类型:System.String
一个由 values 的元素组成的字符串,这些元素以 separator 字符串分隔。

看下面的例子,用StringBuilder来实现串联一组字符串:

string[] parts = { "Apple", "Orange", "Banana", "Pear", "Peach" };


var builder = new StringBuilder();

for (int i = 0; i < parts.Length; i++)
{
    builder.Append(parts[i]);


    // 将最后一个','去掉

    if (i != parts.Length - 1)
    {
        builder.Append(", ");
    }
}


// 结果是 "Apple, Orange, Banana, Pear, Peach"

var result = builder.ToString();

用 string.Join() 可以轻松实现:
 
string[] parts = { "Apple", "Orange", "Banana", "Pear", "Peach" };
 var result = string.Join(", ", parts);
 
很多人可以没有意识到 Join() 可以合并任何类型,如 int, DateTime, double, 或其他自定义的类型! 
当调用 string.Join() 合并非字符串的数值时,它实际上会让每一个元素 ToString().  也就是说这些元素 ToString() 的定义是符合你的需求的才行 – 虽然大部分asp.net库中的类型都已经有了.
举例子:

// 合并整型 "1,2,3,4,5,6,7,8,9,10"


var numsFromOneToTen = string.Join(",", Enumerable.Range(1, 10));


// 合并不同类型的数值 ==> "1-3.1415927-9/16/2011 12:52:22 PM"

var variousObjects = string.Join("-", new object[] { 1, 3.1415927, DateTime.Now });
最后, Join() 明显是支持 IEnumerable<T> 和 object[], string[]:

string[] arr = { "one", "two", "three" };
Console.WriteLine(string.Join(",", arr)); 

//.net 4.0 中你可以直接列出所有数值,不必要生成数组
var numsFromOneToTen = string.Join(",", "A", "B", "C", "D", "E");

var variousObjects = string.Join("-", 1, 3.1415927, DateTime.Now);
       

结论

如果你想将一个字符串分割或者串联一些元素到一个字符串,想想能否用 Split() 或 Join().  它们在很多方面都非常有用.
更多精彩的相关文章,请阅读喜乐的ASP.NET(Alex Song)

2016年9月20日 星期二

[C#語言入門] explicit (明確轉型) vs. implicit (隱含轉型)

Just a note to myself...

public static explicit operator Monkey(Stone stone) {  }
public static implicit operator Monkey(Stone stone) {  }


explicit MSDN


       static void Main(string[] args)
        { 
            Stone stone = new Stone();
            Monkey m = (Monkey)stone;
            m.Age = 5000;
            Monkey wukongSun = (Monkey)stone; // explicit 明確轉型 (Monkey)
            //Monkey wukongSun = stone;              // implicit 隱含轉型
            Console.WriteLine(wukongSun.Age);
        }




  class Stone
    {
        public int Age;
        
        // Monkey wukongSun = (Monkey)stone;
        public static explicit operator Monkey(Stone stone)
        {
            Monkey m = new Monkey();
            m.Age = stone.Age / 500;
            return m;
        }
    }

    class Monkey
    {
        public int Age;
    }





implicit  MSDN


        // Monkey wukongSun = stone;
        public static implicit operator Monkey(Stone stone)
        {
            Monkey m = new Monkey();
            m.Age = stone.Age / 500;
            return m;
        }





https://www.youtube.com/watch?v=q6yAgdzGAJo