代码之家  ›  专栏  ›  技术社区  ›  wethercotes

是否有一个等价于在F中创建C#隐式运算符的方法?

f# c#
  •  25
  • wethercotes  · 技术社区  · 16 年前

    在C#中,我可以向类添加隐式运算符,如下所示:

    public class MyClass
    {
        private int data;
    
        public static implicit operator MyClass(int i)
        {
            return new MyClass { data = i };
        }
    
        public static implicit operator MyClass(string s)
        {
            int result;
    
            if (int.TryParse(s, out result))
            {
                return new MyClass { data = result };
            }
            else
            {
                return new MyClass { data = 999 };
            }
        }
    
        public override string ToString()
        {
            return data.ToString();
        }
    }
    

    然后我可以将任何需要MyClass对象的函数传递为string或int。 如

    public static string Get(MyClass c)
    {
        return c.ToString();
    }
    
    static void Main(string[] args)
    {
        string s1 = Get(21);
        string s2 = Get("hello");
        string s3 = Get("23");
    }
    

    4 回复  |  直到 16 年前
        1
  •  31
  •   svick Raja Nadar    14 年前

    正如其他人所指出的,在F#中没有办法进行隐式转换。但是,您始终可以创建自己的运算符,以使显式转换(以及重用现有类已定义的任何op_隐式定义)更容易一些:

    let inline (!>) (x:^a) : ^b = ((^a or ^b) : (static member op_Implicit : ^a -> ^b) x)
    

    type A() = class end
    type B() = static member op_Implicit(a:A) = B()
    
    let myfn (b : B) = "result"
    
    (* apply the implicit conversion to an A using our operator, then call the function *)
    myfn (!> A())
    
        2
  •  8
  •   Francesco larlin    16 年前

    隐式转换在类型安全性和类型推断方面存在相当大的问题,因此答案是:不,它实际上是一个有问题的特性。

        3
  •  3
  •   Brian    16 年前

        4
  •  2
  •   Dave Glassborow    7 年前

    另一方面,可以添加隐式或显式静态成员,以便C#可以使用它们。

    type Country =
    | NotSpecified
    | England
    | Wales
    | Scotland
    | NorthernIreland
     with static member op_Implicit(c:Country) = 
       match c with | NotSpecified    -> 0
                    | England         -> 1
                    | Wales           -> 2
                    | Scotland        -> 3
                    | NorthernIreland -> 4
    

    这允许c#用户使用 (int) Wales 例如

        5
  •  0
  •   Mikael Dúi Bolinder bielawski    7 年前

    let casted = TargetClass.op_Implicit sourceObject