<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by MilenaChen on Medium]]></title>
        <description><![CDATA[Stories by MilenaChen on Medium]]></description>
        <link>https://medium.com/@menghsinchen?source=rss-c79db2876604------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PH4nqAAq8zVcmuEaJUf7uQ.jpeg</url>
            <title>Stories by MilenaChen on Medium</title>
            <link>https://medium.com/@menghsinchen?source=rss-c79db2876604------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:59:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@menghsinchen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[[JS] 0.2 + 0.1 不是 0.3]]></title>
            <link>https://menghsinchen.medium.com/js-0-2-0-1-%E4%B8%8D%E6%98%AF-0-3-355a0e3c75a4?source=rss-c79db2876604------2</link>
            <guid isPermaLink="false">https://medium.com/p/355a0e3c75a4</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[MilenaChen]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 15:22:30 GMT</pubDate>
            <atom:updated>2024-11-18T15:22:30.644Z</atom:updated>
            <content:encoded><![CDATA[<p>原本想簡單做一個計算。</p><pre>let x = 0.2 + 0.1;<br>x;  // 0.30000000000000004</pre><p>為什麼？</p><p>像我們平常肉眼看的小數點，是十進位的分數。可以表示分母是 10 的倍數的數字，例如 1/10 是 0.1，1/100 是 0.01 等等。</p><p>JavaScript 使用的是 IEEE-754 浮點數表示法，他是一種二進位的表示法。</p><p>所謂二進位的表示法，則可以精確表示像是 1/2、1/16、1/1024 等等的分數。</p><pre>1/2;    // 0.5<br>1/16;   // 0.0625<br>1/1024; // 0.0009765625</pre><p>然而，對於二進位的表示法來說，卻無法表示 0.1 這樣的一個單純的數字。它可以非常非常的接近 0.1，但實際上它並不是 0.1。</p><pre>0.2 + 0.1; // 0.30000000000000004<br>0.3 - 0.2; // 0.09999999999999998<br>let x = 0.3 - 0.2;<br>let y = 0.2 - 0.1;<br>x === y;   // false<br>x === 0.1; // false<br>y === 0.1; // true</pre><p>但它也可以是 0.1。總之沒有一定。</p><p>需要高精確度的浮點數時，建議化為定點數整數計算。不僅可以提升準確，也可以提升運算速度。</p><p>收工。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=355a0e3c75a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[JS] JavaScript 中的截取文字]]></title>
            <link>https://menghsinchen.medium.com/js-javascript-%E4%B8%AD%E7%9A%84%E6%88%AA%E5%8F%96%E6%96%87%E5%AD%97-6b71e0f48863?source=rss-c79db2876604------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b71e0f48863</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[MilenaChen]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 07:29:32 GMT</pubDate>
            <atom:updated>2024-11-17T07:29:32.802Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript 中有三種擷取字串的方法，分別是：</p><ul><li>slice()</li><li>substring()</li><li>substr()</li></ul><p>來看看具體有什麼區別。</p><pre>// 先定義一個字串<br>let s = &quot;0123456789ABCDEF&quot;;</pre><p>傳入一個正數的情況，看起來大家結果是一樣的，都是從 index 為 3 取起一路到底。</p><pre>s.substring(3) // &#39;3456789ABCDEF&#39;<br>s.slice(3)     // &#39;3456789ABCDEF&#39;<br>s.substr(3)    // &#39;3456789ABCDEF&#39;</pre><p>差別會發生在以下情況：</p><h4>傳入兩個正數</h4><p>substring 和 slice 的第二個參數是指結束的 index（結束的那個字元不顯示）。<br>substr 的第二個參數指的是要取的個數，所以從 3 開始取了 7 個字元。</p><pre>s.substring(3,7) // &#39;3456&#39;<br>s.slice(3,7)     // &#39;3456&#39;<br>s.substr(3,7)    // &#39;3456789&#39;</pre><p>更大的差別發生在他們處理負數的態度。</p><p>substring 會把所有負數都轉為 0。<br>slice 會把所有負數加上字串的長度。<br>substr 會把第一個負數加上字串長度，第二個負數轉為 0。（因為第二個參數是要擷取的長度，所以負數當然是不合理的）</p><p>具體的結果會變這樣：</p><h4>傳入一個負數</h4><p>substring 會把負數轉為 0。<br>slice 會把負數加上字串的長度，-3 + 16 = 13，也可以想成是取最後幾個字元。<br>substr 會把第一個參數加上字串的長度，於是傳入一個負數時的結果會跟 slice 相同。</p><pre>s.substring(-3) // &#39;0123456789ABCDEF&#39; : 相當於 s.substring(0)<br>s.slice(-3)     // &#39;DEF&#39; : 相當於 s.slice(13)<br>s.substr(-3)    // &#39;DEF&#39; : 相當於 s.substr(13)</pre><h4>傳入兩個負數</h4><p>剛才提過，substring 會把所有負數都轉為 0。從 0 開始，0 又不顯示，那就當啥也沒發生。<br>slice 會把所有負數加上字串的長度。<br>substr 把第一個負數加上字串長度，第二個負數變成 0。</p><pre>s.substring(-3,-1) // &#39;&#39; : 相當於 s.substring(0,0)<br>s.slice(-3,-1)     // &#39;DE&#39; : 相當於 s.slice(13,15)<br>s.substr(-3,-1)    // &#39;&#39; : 相當於 s.substr(13,0)</pre><h4>傳入一正一負</h4><p>來預測一下，跟之前的認知有沒有一樣吧。</p><pre>// 先正後負<br>s.substring(-3,2)  // &#39;01&#39; : 相當於 s.substring(0,2)<br>s.slice(-3,2)      // &#39;&#39; : 相當於 s.slice(13,2)<br>s.substr(-3,2)     // &#39;DE&#39; : 相當於 s.substr(13,2)<br><br>// 先負後正<br>s.substring(4,-1)  // &#39;0123&#39; : 相當於 s.substring(4,0)<br>s.slice(4,-1)      // &#39;456789ABCDE&#39; : 相當於 s.slice(4,15)<br>s.substr(4,-1)     // &#39;&#39;: 相當於 s.substr(4,0)</pre><p>休息。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b71e0f48863" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[JS] 來做四捨五入吧]]></title>
            <link>https://menghsinchen.medium.com/js-%E4%BE%86%E5%81%9A%E5%9B%9B%E6%8D%A8%E4%BA%94%E5%85%A5%E5%90%A7-ac4ab334b513?source=rss-c79db2876604------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac4ab334b513</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[MilenaChen]]></dc:creator>
            <pubDate>Sat, 16 Nov 2024 07:59:53 GMT</pubDate>
            <atom:updated>2024-11-16T08:28:26.658Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript 透過定義 Math 物件支援複雜的數學運算，其中有常見的：</p><pre>Math.round(.6) // =&gt; 1 : 四捨五入<br>Math.ceil(.6)  // =&gt; 1 : 向上捨入/無條件進位 (round up)<br>Math.floor(.6) // =&gt; 0 : 向下捨入/無條件捨去 (round down)</pre><p>在 ES6 之後，定義了更多函式，例如：</p><pre>Math.trunc(.6) // =&gt; 0 : 截斷小數部分轉換為整數 (truncate)</pre><p>這時心中就出現了一個疑問。</p><h4>所以 floor 跟 trunc 的差別是什麼？</h4><p>調查了一下，其實答案很簡單，用負數就可以簡單看出差別。</p><p>我們定義一些數字，來看看函式的結果。</p><pre>// 定義一個數字陣列<br>let numbers = [ 8.1, 8.7, -8.1, -8.7 ];<br><br>// 對每個成員印出各種計算結果<br>let results = [];<br>numbers.forEach((value, i) =&gt; {<br>    results.push(Math.round(value).toString().padStart(2, &#39; &#39;));<br>    results.push(Math.ceil(value).toString().padStart(2, &#39; &#39;));<br>    results.push(Math.floor(value).toString().padStart(2, &#39; &#39;));<br>    results.push(Math.trunc(value).toString().padStart(2, &#39; &#39;));<br>    console.log(results);<br>    results = [];<br>});</pre><p>印出來的結果長這樣：</p><pre>// 依序是 round, ceil, floor, trunc<br>[&#39; 8&#39;, &#39; 9&#39;, &#39; 8&#39;, &#39; 8&#39;]  // 8.1<br>[&#39; 9&#39;, &#39; 9&#39;, &#39; 8&#39;, &#39; 8&#39;]  // 8.7<br>[&#39;-8&#39;, &#39;-8&#39;, &#39;-9&#39;, &#39;-8&#39;]  // -8.1<br>[&#39;-9&#39;, &#39;-8&#39;, &#39;-9&#39;, &#39;-8&#39;]  // -8.7</pre><p>白話文：<strong>正數的 trunc 是 floor，負數的 trunc 是 ceil。</strong></p><p>打完收工。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac4ab334b513" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[XML] 來學習 XML 吧]]></title>
            <link>https://menghsinchen.medium.com/xml-%E4%BE%86%E5%AD%B8%E7%BF%92-xml-%E5%90%A7-4b344210bd02?source=rss-c79db2876604------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b344210bd02</guid>
            <dc:creator><![CDATA[MilenaChen]]></dc:creator>
            <pubDate>Wed, 13 Sep 2023 14:00:10 GMT</pubDate>
            <atom:updated>2023-09-13T14:00:10.345Z</atom:updated>
            <content:encoded><![CDATA[<p>XML（Extensible Markup Language）是一種標記式語言，乍看之下跟網頁的 HTML（Hypertext Markup Language）長得很像。</p><blockquote>XML 和 HTML 的區別：</blockquote><ul><li>XML：是用來儲存資料。專注在 what data is。</li><li>HTML：是用來呈現資料。專注在 how data looks。</li><li>HTML 有 predefined 的 tags，而 XML 沒有。</li></ul><blockquote>XML 的成員</blockquote><pre>&lt;?xml version=&quot;1.0&quot;?&gt;<br>&lt;catalog&gt;<br>   &lt;book id=&quot;bk101&quot;&gt;<br>      &lt;author&gt;Gambardella, Matthew&lt;/author&gt;<br>      &lt;title&gt;XML Developer&#39;s Guide&lt;/title&gt;<br>      &lt;genre&gt;Computer&lt;/genre&gt;<br>      &lt;price&gt;44.95&lt;/price&gt;<br>      &lt;publish_date&gt;2000-10-01&lt;/publish_date&gt;<br>      &lt;description&gt;An in-depth look at creating applications <br>      with XML.&lt;/description&gt;<br>   &lt;/book&gt;<br>   &lt;book id=&quot;bk102&quot;&gt;<br>      &lt;author&gt;Ralls, Kim&lt;/author&gt;<br>      &lt;title&gt;Midnight Rain&lt;/title&gt;<br>      &lt;genre&gt;Fantasy&lt;/genre&gt;<br>      &lt;price&gt;5.95&lt;/price&gt;<br>      &lt;publish_date&gt;2000-12-16&lt;/publish_date&gt;<br>      &lt;description&gt;A former architect battles corporate zombies, <br>      an evil sorceress, and her own childhood to become queen <br>      of the world.&lt;/description&gt;<br>   &lt;/book&gt;<br>&lt;/catalog&gt;</pre><p>上面是一個簡單的 <a href="https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ms762271(v=vs.85)">XML 範例</a>。</p><h4>XML Declaration（聲明）</h4><p>&lt;?xml version=”1.0”?&gt; 表述了文件的一些資訊。</p><h4>Tag（標記）</h4><p>一個 Tag 是以 &lt; 開頭，以 &gt; 結尾的。Tag 的名字不可以有空格或特殊字元。Tag 可以分為三類。</p><ul><li>start-tag: &lt;book&gt; 表示一個節點開始。</li><li>eng-tag: &lt;/book&gt; 表示一個節點結束。</li><li>empty-element tag: &lt;book /&gt; 同事表示開始和結束，沒有內文。</li></ul><p>Tag 必須成對出現，一個 start-tag 必須搭配一個 end-tag。如果是沒有內文的時候，可以簡寫成 empty-element tag。</p><p>&lt;book&gt;&lt;/book&gt; 和 &lt;book /&gt; 的寫法在意義上是完全相同的。</p><h4>Element（元素）</h4><p>元素也就是文件邏輯，可以是一個 start-tag 和一個 end-tag 之間，也可以是一個 empty-element tag。</p><p>&lt;title&gt;Midnight Rain&lt;/title&gt; 是一個元素。</p><p>&lt;title /&gt; 也是一個元素。</p><p>而根元素包含其他所有的元素。</p><h4>Attribute（屬性）</h4><p>是一種標記方式。</p><p>&lt;book id=”bk102”&gt; 中，id 是 Attribute，”bk102” 是 Value。</p><blockquote>樹狀結構</blockquote><p>不多說。</p><pre>&lt;root&gt;<br>  &lt;child&gt;<br>    &lt;subchild&gt;.....&lt;/subchild&gt;<br>  &lt;/child&gt;<br>&lt;/root&gt;</pre><p>打完收工。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b344210bd02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[C#] 來開一個 WPF 專案吧]]></title>
            <link>https://menghsinchen.medium.com/c-%E4%BE%86%E9%96%8B%E4%B8%80%E5%80%8B-wpf-%E5%B0%88%E6%A1%88%E5%90%A7-77f289992ddb?source=rss-c79db2876604------2</link>
            <guid isPermaLink="false">https://medium.com/p/77f289992ddb</guid>
            <category><![CDATA[wpf]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[MilenaChen]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 15:30:08 GMT</pubDate>
            <atom:updated>2023-08-23T15:30:08.447Z</atom:updated>
            <content:encoded><![CDATA[<p>原來新工作不是要寫 WinForm，是要寫 WPF。</p><p>我沒寫過 WPF 啊！！！！！！</p><p>二話不說先新建一個專案。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*paxitTk1b4IhRhK2r1nfzw.png" /></figure><p>開起來長這樣。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52XuxT9Seo8V44SqQNOQSQ.png" /></figure><p>然後呢...現在要怎麼辦。</p><p>不然就跟 WinForm 一樣，先閉著眼睛拉一個 button 進來吧。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*khRAp6USJttTTRnTJxM8Qw.png" /></figure><p>然後在 button 上點兩下。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3PGEz8L0qKhNB8fT2FR-Jw.png" /></figure><p>好像就跟 WinForm 一樣？</p><p>不曉得 MessageBox.Show() 能不能用？跑跑看。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*XWg5HE4hfLmT_ILB0wYHNg.png" /></figure><p>根本就一樣......</p><p>感謝<a href="https://www.youtube.com/watch?v=i0vAcAx2r7k">這支影片</a>。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77f289992ddb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[C#] 來處理日期和時間吧]]></title>
            <link>https://menghsinchen.medium.com/c-%E4%BE%86%E8%99%95%E7%90%86%E6%97%A5%E6%9C%9F%E5%92%8C%E6%99%82%E9%96%93%E5%90%A7-f41559800c76?source=rss-c79db2876604------2</link>
            <guid isPermaLink="false">https://medium.com/p/f41559800c76</guid>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[MilenaChen]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 04:06:44 GMT</pubDate>
            <atom:updated>2023-08-20T04:06:44.125Z</atom:updated>
            <content:encoded><![CDATA[<p>明天就要上班了，再讀一點書抗焦慮。</p><blockquote>DateTime</blockquote><p>DateTime 是一種 struct。來測一下各種 DateTime。</p><pre>static void Main()<br>{<br>    DateTime birthday = new DateTime(1981, 7, 31);<br>    DateTime utcNow = new DateTime();<br>    utcNow = DateTime.UtcNow;<br>    DateTime now = new DateTime();<br>    now = DateTime.Now;<br>    DateTime tomorrow = now.AddDays(1);<br><br>    Console.WriteLine(birthday.ToShortDateString());  //1981/7/31<br>    Console.WriteLine(utcNow.ToString());  //2023/8/20 上午 03:42:37<br>    Console.WriteLine(now.ToLongTimeString());  //上午 11:42:37<br>    Console.WriteLine(tomorrow.ToLongDateString());  //2023年8月21日<br><br>    Console.ReadKey();<br>}</pre><blockquote>TimeSpan</blockquote><p>TimeSpan 是時間相減後拋出來的型別。有兩種方式可以算哈利現在的年紀。</p><p>用 DateTime 的 Subtract() 方法。</p><pre>static void Main()<br>{<br>    DateTime birthday = new DateTime(1981, 7, 31);<br>    DateTime today = new DateTime();<br>    today = DateTime.Today;<br>    TimeSpan age = today.Subtract(birthday);  //Subtract<br><br>    Console.WriteLine($&quot;Harry is {age} years old.&quot;);<br>    Console.ReadKey();<br>}</pre><p>用減的。</p><pre>static void Main()<br>{<br>    DateTime birthday = new DateTime(1981, 7, 31);<br>    DateTime today = new DateTime();<br>    today = DateTime.Today;<br>    TimeSpan age = today - birthday;  //minus<br><br>    Console.WriteLine($&quot;Harry is {age} years old.&quot;);<br>    Console.ReadKey();<br>}</pre><p>結果減出來是這樣。看上去有些不太對勁。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*J7dSYhoxBZH1NJ7ikb9ijA.png" /></figure><p>再加個 Days 轉看看會變成啥。</p><pre>static void Main()<br>{<br>    DateTime birthday = new DateTime(1981, 7, 31);<br>    DateTime today = new DateTime();<br>    today = DateTime.Today;<br>    int age = (today - birthday).Days;  //convert to days<br><br>    Console.WriteLine($&quot;Harry is {age} years old.&quot;);<br>    Console.ReadKey();<br>}</pre><p>還是 15360。看來 TimeSpan 出來的整數部分是天數石錘了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*ws5oT_vkdizruUmU9TPgxg.png" /></figure><p>那既然現在 .Days 之後出來是 int 天數，就拿來除以個 365 吧。</p><pre>static void Main()<br>{<br>    DateTime birthday = new DateTime(1981, 7, 31);<br>    DateTime today = new DateTime();<br>    today = DateTime.Today;<br>    int age = (today - birthday).Days / 365;<br><br>    Console.WriteLine($&quot;Harry is {age} years old.&quot;);<br>    Console.ReadKey();<br>}</pre><p>跑一下。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*bQhjaQWTq0Dsqmq3nsWROg.png" /></figure><p>正常多了。</p><p>注意在還沒有 .Days 之間，TimeSpan 型別是沒辦法直接除以 365 的，也沒辦法用 Convert.ToInt32 轉型喔。</p><p>打完收工。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f41559800c76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[C#] 來複習物件導向的繼承吧]]></title>
            <link>https://menghsinchen.medium.com/c-%E4%BE%86%E8%A4%87%E7%BF%92%E7%89%A9%E4%BB%B6%E5%B0%8E%E5%90%91%E7%9A%84%E7%B9%BC%E6%89%BF%E5%90%A7-fa90e96d8?source=rss-c79db2876604------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa90e96d8</guid>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[MilenaChen]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 13:33:54 GMT</pubDate>
            <atom:updated>2023-08-20T09:46:35.344Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>繼承 Inheritance</blockquote><p>物件導向中，繼承是一個重要的概念。透過繼承，可以讓以定義的類別新增、修改原有的功能。</p><p>假設我們原本就有一個叫 Person 的 class，是這樣定義的。</p><pre>public class Person<br>{<br>    public string Id { get; set; }<br>    public string Name { get; set; }<br>    public string Gender { get; set; }<br>    public string Nationality { get; set; }<br>    public int Age { get; set; }<br>    public void Play()<br>    {<br>        Console.WriteLine(&quot;I play sports.&quot;);<br>    }<br>}</pre><p>我們另外想要建立一個叫 British 的 class，他們擁有 Person 的屬性和方法，但他們也可以分別有特別只屬於自己的屬性和方法。</p><p>這時，Person 就是「父類別」或「基底類別（Base class）」，British 是「子類別」或「衍生類別（Derived class）」。</p><p>C# 是單一繼承制。每個子類別只能有一個父類別。</p><blockquote>通化（Generalization）和特化（Specialization）關係。</blockquote><p>先有 Person、然後衍生了 British 的過程稱為「通化」；相反的，British 和 American 和其他因為有部分不同，分別是 Person 的「特化」表現。</p><p>「通化」表達了一種 is_a（is a kind of）的關係。British <em>is_a</em> Person。</p><p>當衍生的類別繼承了基底類別時，也可以修改基底類別的某一部份特性，這種概念稱為「覆寫（override）」。</p><pre>public class British : Person<br>{<br>    public void Play()<br>    {<br>        Console.WriteLine(&quot;I play football.&quot;);  //override<br>    }<br>}</pre><blockquote>組合（Composition）關係</blockquote><p>組合是另外一種繼承的關係，是 has_a 的關係。例如，Teacher 和 Student 的子類別都衍生自 School 父類別。School <em>has_a</em> Teacher。School <em>has_a</em> Student。</p><p>在 WinForm 裡面，我們常會看到 Form1.cs 和 Form1.Designer.cs 組成一個 Form1 class。這兩個檔案屬於同一個 namespace。</p><p>Form1.cs:</p><pre>namespace AtomicForm<br>{<br>    public partial class Form1 : Form<br>    {<br>        public Form1()<br>        {<br>            InitializeComponent();<br>        }<br><br>        private void Form1_Load(object sender, EventArgs e)<br>        {<br><br>        }<br>    }<br>}</pre><p>Form1.Designer.cs:</p><pre>namespace AtomicForm<br>{<br>    partial class Form1<br>    {<br>        //以下省略</pre><blockquote>this</blockquote><p>將類別實體化成物件時，使用 this 關鍵字，就可以指向這個物件本身，或是與物件相關的成員。</p><p>例如我在 British 這個 class 的建構式中加上 this.Nationality 來設定 British 物件的國籍。</p><pre>public class British : Person<br>{<br>    public British()<br>    {<br>        this.Nationality = &quot;British&quot;;<br>    }<br>    public void Play()<br>    {<br>        Console.WriteLine(&quot;I play football.&quot;);<br>    }<br>}</pre><p>用 British class 實體化一個物件。</p><pre>static void Main()<br>{<br>    British cumberbatch = new British();<br>    Console.WriteLine(cumberbatch.Nationality);  //British<br>    cumberbatch.Play();  //I play football.<br>    Console.ReadKey();<br>}</pre><blockquote>設定子類別中的成員為唯讀</blockquote><p>在上面的例子，由於 Nationality 在 Person 中定義為 { get; set; }，所以我們還是可以惡搞 cumberbatch 的國籍。</p><pre>static void Main()<br>{<br>    British cumberbatch = new British();<br>    cumberbatch.Nationality = &quot;American&quot;;<br>    Console.WriteLine(cumberbatch.Nationality);  //American<br>    Console.ReadKey();<br>}</pre><p>我們可以把 British 裡的 Nationality 定義為唯讀。</p><pre>public class British : Person<br>{<br>    public string Nationality { get { return &quot;British&quot;; } }<br>    public void Play()<br>    {<br>        Console.WriteLine(&quot;I play football.&quot;);<br>    }<br>}</pre><p>這時候的主程式就會報錯了：</p><p>Compiler error CS0200: Property or indexer ‘property’ cannot be assigned to — it is read only.</p><pre>static void Main()<br>{<br>    British cumberbatch = new British();<br>    cumberbatch.Nationality = &quot;American&quot;;  //Compiler error CS0200<br>    Console.WriteLine(cumberbatch.Nationality);<br>    Console.ReadKey();<br>}</pre><blockquote>繼承機制底下的方法的多形（Polymorphism）</blockquote><p>上面的練習裡，由於父類別 Person 和子類別 British 都有定義 Nationality 屬性和 Play() 方法，在 British 中會有錯誤提醒：</p><p>CS0108: ‘member1’ hides inherited member ‘member2’. Use the new keyword if hiding was intended.</p><p>其實他是擔心我們不小心取了相同名字的方法而不自知。要讓這個提醒消失的話，有兩個方法：</p><ul><li>在子類別方法的存取修飾詞前面加上 new。</li><li>在父類別方法的存取修飾詞後加 virtual，在子類別方法加 override。</li></ul><p>這兩種方式實際上是有一點差異的，但我還沒有搞得非常清楚。但書上是這樣寫的：</p><ul><li>new 是「隱藏」了基底類別成員。</li><li>virtual/override 是「擴充」了基底列別成員。</li></ul><blockquote>用 new 隱藏基底類別的成員</blockquote><p>在子類別中，加上 new 關鍵字，讓 IDE 知道我們是故意的。</p><pre>public class British : Person<br>{<br>    new public string Nationality { get { return &quot;British&quot;; } }<br>    new public void Play()<br>    {<br>        Console.WriteLine(&quot;I play football.&quot;);<br>    }<br>}</pre><blockquote>用 virtual/override 擴充基底類別的成員</blockquote><p>當基底類別有 virtual 關鍵字，衍生類別有 override 關鍵字時，呼叫衍生類別時，就會呼叫自己的方法，而不是基底類別的方法。</p><p>在使用 override 覆寫時，不能變更 virtual 方法的存與範圍，也就是要使用相同的存取修飾詞，原本是 public 就要跟著 public，原本是 private 就要跟著是 private。</p><p>virtual/override 要放在存取修飾詞（public、private…）之後，回傳類別之前。</p><p>virtual 不能與 static、abstract、private、override 等共用。</p><p>基底類別範例：</p><pre>public class Person<br>{<br>    public virtual void Play()  //virtual<br>    {<br>        Console.WriteLine(&quot;I play sports.&quot;);<br>    }<br>}</pre><p>衍生類別範例：</p><pre>public class British : Person<br>{<br>    public override void Play()  //override<br>    {<br>        Console.WriteLine(&quot;I play football.&quot;);<br>    }<br>}</pre><blockquote>base</blockquote><p>類別之間可以繼承，但建構函式卻是各自獨立。基底類別和衍生類別都有自己的建構函式，用來初始化該類別的物件，建構函式不會產生繼承。（靜態方法不能使用 base）</p><p>當基底類別有建構函式時，衍生類別也得要有建構函式才行。如果基底類別的建構函是有參數，衍生類別也必須宣告型別和參數，再以 base() 方法帶入參數名稱。</p><p>如果基底類別的建構函式沒有參數，衍生類別可以選擇建構函式是否要使用 base() 方法。</p><p>打完收工。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa90e96d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[C#] 傳值和傳址]]></title>
            <link>https://menghsinchen.medium.com/c-%E5%82%B3%E5%80%BC%E5%92%8C%E5%82%B3%E5%9D%80-7cb604c6f10a?source=rss-c79db2876604------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cb604c6f10a</guid>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[MilenaChen]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 12:59:13 GMT</pubDate>
            <atom:updated>2023-08-18T12:59:13.114Z</atom:updated>
            <content:encoded><![CDATA[<h3>[C#] 方法參數的傳遞機制</h3><p>當透過 return 使用方法的時候，一次只能回傳一個結果。</p><p>方法之間如果需要回傳多個參數值，則需要使用「參數」和「引數」。</p><h4>形式參數（Formal parameter）</h4><p>簡稱「參數」，在定義方法時，括號內有指定對象，設定參數接收資料，進入方法主體執行敘述或運算。</p><h4>實際引數（Actual argument）</h4><p>簡稱「引數」，在實際程式中，負責呼叫方法，傳遞資料。</p><blockquote>傳值呼叫（Passing by Value）</blockquote><p>下面範例中，DoubleSalary(int salary) 的 salary 就是「參數」。</p><p>在 Main() 裡面負責呼叫那個 DoubleSalary() 方法的 salaryToday，就是「引數」。</p><pre>public static int DoubleSalary(int salary)<br>{<br>    salary = salary * 2;<br>    return salary;<br>}<br><br>static void Main()<br>{<br>    int salaryToday = 10000;<br>    int salaryTomorrow = DoubleSalary(salaryToday);<br>    Console.WriteLine(salaryToday);  //10000<br>    Console.WriteLine(salaryTomorrow);  //20000<br>    Console.ReadKey();<br>}</pre><p>傳遞參數時，傳遞方（呼叫別人的方法）會將「引數」內容的值複製一份「參數」出來，再把副本給接收方（被呼叫的方法）。</p><p>「引數」和「參數」分別佔據記憶的不同位置。所以，當被呼叫的方法中的「參數」被修改，並不會影響實際的「引數」。這種方法適用於希望方法內的結果不會影響方法外的變數時使用。</p><p>DoubleSalary() 裡的參數 salary 的變動，和外面的引數 salaryToday 的變動是沒有關係的，改變 salary 並不會改變 salaryToday。</p><blockquote>傳址呼叫（Passing by Reference）</blockquote><p>傳址呼叫是當「引數」在呼叫方法的時候，把記憶體的位置傳給「參數」，連同記憶體儲存的資料也一起傳送。因為傳送的是記憶體位置，所以當「參數」的值改變時，「引數」的值也會一起被改變。</p><p>使用傳址呼叫的時候，「引數」和「參數」都要在型別前面加 ref。而且「引數」必須要有初始值。</p><pre>public static int DoubleSalary(ref int salary)  //ref<br>{<br>    salary = salary * 2;<br>    return salary;<br>}<br><br>static void Main()<br>{<br>    int salaryToday = 10000;  //actual argument has a value<br>    int salaryTomorrow = DoubleSalary(ref salaryToday);  //ref<br>    Console.WriteLine(salaryToday);  //20000<br>    Console.WriteLine(salaryTomorrow);  //20000<br>    Console.ReadKey();<br>}</pre><blockquote>傳出參數（Output parameter）</blockquote><p>傳出參數和傳址呼叫一樣，「引數」和「參數」佔用的是相同的記憶體位置。只是，傳出參數的「參數」不必先初始化就可以傳遞。</p><p>不過，指派變數值的動作必須在被呼叫的方法中完成。</p><pre>public static int DoubleSalary(out int salary, out int bonus)<br>{<br>    salary = 10000;<br>    bonus = 10000 * 2;<br>    int total = salary + bonus;<br>    return total;<br>}<br><br>static void Main()<br>{<br>    int salaryToday;<br>    int bonusToday;<br>    int salaryTomorrow = DoubleSalary(out salaryToday, out bonusToday);<br>    Console.WriteLine(salaryToday);  //10000<br>    Console.WriteLine(bonusToday);  //20000<br>    Console.WriteLine(salaryTomorrow);  //30000<br>    Console.ReadKey();<br>}</pre><p>打完收工。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cb604c6f10a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[C#] 方法的簡寫方式]]></title>
            <link>https://menghsinchen.medium.com/c-%E6%96%B9%E6%B3%95%E7%9A%84%E7%B0%A1%E5%AF%AB%E6%96%B9%E5%BC%8F-18156de4c38b?source=rss-c79db2876604------2</link>
            <guid isPermaLink="false">https://medium.com/p/18156de4c38b</guid>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[MilenaChen]]></dc:creator>
            <pubDate>Wed, 16 Aug 2023 07:04:31 GMT</pubDate>
            <atom:updated>2023-08-16T07:04:31.361Z</atom:updated>
            <content:encoded><![CDATA[<p>一般定義的方法：</p><pre>public int Addition(int num1, int num2)<br>{<br>    return num1 + num2;<br>}</pre><p>如果只有單一敘述，可以用 =&gt;，並省略大括號和 return：</p><pre>public int Addition(int num1, int num2) =&gt; num1 + num2;</pre><p>沒有什麼幹勁的一天。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18156de4c38b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[C#] 來了解靜態吧]]></title>
            <link>https://menghsinchen.medium.com/c-%E4%BE%86%E4%BA%86%E8%A7%A3%E9%9D%9C%E6%85%8B%E9%A1%9E%E5%88%A5%E5%90%A7-ad09d3946cd7?source=rss-c79db2876604------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad09d3946cd7</guid>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[MilenaChen]]></dc:creator>
            <pubDate>Tue, 15 Aug 2023 15:41:22 GMT</pubDate>
            <atom:updated>2023-08-16T07:14:34.702Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>靜態類別</blockquote><p>靜態類別（Static Class）和一般類別有什麼不同？</p><ul><li>靜態類別的前面會加上 static 關鍵字。</li><li>靜態類別的成員－屬性、方法等，也必須定義成 static。</li><li>靜態類別屬於密封類別（Sealed Class），無法繼承。</li><li>靜態類別不能用 new 運算子來實體化類別，也不會有執行個體。</li><li>存取靜態類別時，只能使用靜態類別名稱。</li></ul><p>靜態類別由於不需要 new 出來才能使用，它和一般類別的不同，是它在程式打開執行的時候就已經佔據記憶體了。如果有一個方法是寫在一般類別裡面，會在 new 出這個物件的時候才佔據記憶體，並且也會隨著解構而釋放。但靜態類別所佔據的記憶體，有點類似全域變數的概念，會在最後程式關掉的時候才釋放。</p><blockquote>靜態屬性</blockquote><p>在一般類別當中，也可以替成員加入 static 關鍵字，來定義成靜態成員，它們是所有物件所共有，避免浪費記憶體空間，並且提供各個獨立的物件之間互相溝通的管道。</p><p>不過，存取靜態成員時，只能以類別名稱，無法以執行個體做存取動作。</p><p>一般類別在宣告靜態欄位的時候，編譯器在執行的時候，只會為每個類別配置一個屬於該屬性的記憶體空間。</p><pre>public class Student<br>{<br>    public static int Count { get; private set; }   //static property<br>    public string Name { get; set; }<br>    public string House { get; set; }<br>    public Student(string name, string house)<br>    {<br>        Name = name;<br>        House = house;<br>        Count++;    //happens while an object being created<br>        Console.WriteLine($&quot;Your name is {Name}. We have {Count} students now.&quot;);<br>    }<br>}</pre><p>試著建兩個 Student 的物件出來跑跑看。</p><pre>static void Main(string[] args)<br>{<br>    Student harry = new Student(&quot;Harry&quot;, &quot;Gryffindor&quot;);<br>    Student ron = new Student(&quot;Ron&quot;, &quot;Gryffindor&quot;);<br>    Console.ReadKey();<br>}</pre><p>結果。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*oxd_OYe-caQ89SDQbMwc2A.png" /></figure><blockquote>靜態方法</blockquote><p>靜態方法也是一樣，前面要加上一個 static。</p><p>一般類別和靜態類別都可以擁有靜態方法。</p><pre>public class Student<br>{<br>    public static int Count { get; private set; }<br>    public string Name { get; set; }<br>    public string House { get; set; }<br>    public Student(string name, string house)<br>    {<br>        Name = name;<br>        House = house;<br>        Count++;<br>    }<br><br>    //static method<br>    public static void Announce() =&gt; Console.WriteLine($&quot;We have {Count} students now.&quot;);<br><br>    //non-static method<br>    public void Introduce() =&gt; Console.WriteLine($&quot;I am {Name} from {House}.&quot;);<br>    public void Spell() =&gt; Console.WriteLine(&quot;Wingardium Leviosa!&quot;);<br>}</pre><p>靜態方法可以在沒有 new 出物件的情況下就被調用，但非靜態方法只有在 new 出這個物件之後才能被自己調用。</p><pre>static void Main(string[] args)<br>{<br>    Student harry = new Student(&quot;Harry&quot;, &quot;Gryffindor&quot;);<br>    Student ron = new Student(&quot;Ron&quot;, &quot;Gryffindor&quot;);<br>    harry.Introduce();  //call non-static method<br>    Student.Announce(); //call static method<br>    Console.ReadKey();<br>}</pre><p>打完收工。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad09d3946cd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>