How can I duplicate the F# discriminated union type in C#?

后端 未结 6 942
抹茶落季
抹茶落季 2020-12-09 18:10

I\'ve created a new class called Actor which processes messages passed to it. The problem I am running into is figuring out what is the most elegant way to pass related but

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-09 18:50

    A long shot, but anyway..

    I am assuming that discriminated-union is F# for ADT (Abstract Data Type). Which means the type could be one of several things.

    In case there are two, you could try and put it in a simple generic class with two type parameters:

     public struct DiscriminatedUnion
     {   
          public DiscriminatedUnion(T1 t1) { value = t1; }
          public DiscriminatedUnion(T2 t1) { value = t2; }
    
    
          public static implicit operator T1(DiscriminatedUnion du) {return (T1)du.value; }
          public static implicit operator T2(DiscriminatedUnion du) {return (T2)du.value; }
    
          object value;
     }
    

    To make it work for 3 or more, we need to replicate this class a number of times. Any one has a solution for function overloading depending on the runtime type?

提交回复
热议问题