ufcpp / UfcppSample

http://ufcpp.net/ 向けのサンプル
Apache License 2.0
136 stars 39 forks source link

patterns #209

Closed ufcpp closed 5 years ago

ufcpp commented 5 years ago

前にブログ書いたやつ: https://ufcpp.net/blog/2018/12/cs8patterns/

ページ追加・既存ページ修正

書くこと

ufcpp commented 5 years ago
struct X
{
    public void Deconstruct() { }
    public void Deconstruct(out int a) => a = 0;
    public void Deconstruct(out int a, out int b) => (a, b) = (0, 0);
}
Console.WriteLine(x is ());
Console.WriteLine(x is var ());
Console.WriteLine(x is X ());
//Console.WriteLine(x is (1)); // これは Deconstruct 見ない。 x is 1 と同じ意味。エラーに。
Console.WriteLine(x is (1) _);
Console.WriteLine(x is (0) _);
Console.WriteLine(x is X (1));
Console.WriteLine(x is X (0));
//Console.WriteLine(x is var (0)); // これはダメ
Console.WriteLine(x is (_, _));
Console.WriteLine(x is (1, _));
Console.WriteLine(x is (0, 0));
ufcpp commented 5 years ago

オーバーロード解決はせず

ufcpp commented 5 years ago
using System;
using System.Runtime.CompilerServices;

class X : ITuple
{
    public object this[int index] => index;
    public int Length => 3;
}

class Program
{
    static void Main()
    {
        M(new X());
    }

    static void M(object x)
    {
        if (x is (int a, int b, int c))
        {
            // マッチする。 (0, 1, 2) が表示される。
            Console.WriteLine((a, b, c));
        }
    }
}
ufcpp commented 5 years ago

https://ufcpp.net/study/csharp/datatype/patterns/