Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Last active September 20, 2016 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ufcpp/b45f521ee52cb01c9e71181142a9f7f6 to your computer and use it in GitHub Desktop.
Save ufcpp/b45f521ee52cb01c9e71181142a9f7f6 to your computer and use it in GitHub Desktop.
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 だったとき
}
}
}
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