Last active
September 20, 2016 08:25
-
-
Save ufcpp/b45f521ee52cb01c9e71181142a9f7f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
// こう書きたい: | |
#if false | |
class X = int | string | Exception; // int と string と Exception の union | |
static void F(X x) | |
{ | |
switch (x) | |
{ | |
case int n: // x が int だったとき | |
case string s: // x が string だったとき | |
case Exception e: // x が Exception だったとき | |
} | |
} | |
#endif | |
// こう展開すればまあ、似たようなことはできる: | |
enum XDiscriminator | |
{ | |
@int, | |
@string, | |
Exception, | |
} | |
struct X | |
{ | |
public XDiscriminator type; | |
public object value; | |
} | |
static void F(X x) | |
{ | |
switch (x.type) | |
{ | |
case XDiscriminator.@int: var n = (int)x.value; // x が int だったとき | |
case XDiscriminator.@string: var n = (string)x.value; // x が string だったとき | |
case XDiscriminator.Exception: var n = (Exception)x.value; // x が Exception だったとき | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
// こう書きたい: | |
#if false | |
class X = A | B; // A, B もこれから定義するものとして、そのA, Bの union が X | |
static void F(X x) | |
{ | |
switch (x) | |
{ | |
case A a: // x が A だったとき | |
case B b: // x が B だったとき | |
} | |
} | |
#endif | |
// こう展開すればまあ、似たようなことはできる: | |
abstract class X { } | |
{ | |
private X() { } | |
// .NETの型システム自体が型弁別用のID持ってるようなものなので、union1.csの方で言うDiscriminatorは自作する必要なし | |
// それぞれの型を X から派生させるだけ。 | |
public class A : X { } | |
public class B : X { } | |
} | |
static void F(X x) | |
{ | |
switch (x) | |
{ | |
case X.A a: // x が A だったとき | |
case X.B b: // x が B だったとき | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment