Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- using System.Runtime.InteropServices;
- using CT1 = Int32;
- using CT2 = System.Collections.Generic.List<Int32>;
- public struct ConstantTaggedUnion
- {
- // System.TypeLoadException: Could not load type '_Union' because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field.
- public static void test()
- {
- ConstantTaggedUnion foo = 1;
- Debug.Assert(foo.GetUnionType() == typeof(int));
- { int bar = (int) foo; }
- foo = new CT2();
- }
- public ConstantTaggedUnion(CT1 value) { _union=new _Union{Type1=value}; _id=1; }
- public ConstantTaggedUnion(CT2 value) { _union=new _Union{Type2=value}; _id=2; }
- public CT1 Type1 { get{ if(_id!=1)_TypeError(1); return _union.Type1; } set{ _union.Type1=value; _id=1; } }
- public CT2 Type2 { get{ if(_id!=2)_TypeError(2); return _union.Type2; } set{ _union.Type2=value; _id=2; } }
- public static explicit operator CT1(ConstantTaggedUnion value) { return value.Type1; }
- public static explicit operator CT2(ConstantTaggedUnion value) { return value.Type2; }
- public static implicit operator ConstantTaggedUnion(CT1 value) { return new ConstantTaggedUnion(value); }
- public static implicit operator ConstantTaggedUnion(CT2 value) { return new ConstantTaggedUnion(value); }
- public byte Tag {get{ return _id; }}
- public Type GetUnionType()
- {switch(_id){
- case 1: return typeof(CT1);
- case 2: return typeof(CT2);
- default: return typeof(void);
- }}
- public override string ToString()
- {switch(_id){
- case 1: return _union.Type1.ToString();
- case 2: return _union.Type2.ToString();
- default: return "void";
- }}
- _Union _union;
- byte _id;
- void _TypeError(byte id) { throw new InvalidCastException(/* todo */); }
- [StructLayout(LayoutKind.Explicit)]
- struct _Union
- {
- [FieldOffset(0)] public CT1 Type1;
- [FieldOffset(0)] public CT2 Type2;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement