Is there an equivalent to creating a C# implicit operator in F#?

北城以北 提交于 2020-01-28 19:46:24

问题


In C# I can add implicit operators to a class as follows:

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();
    }
}

Then I can pass any function that is expecting a MyClass object a string or an int. eg

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");
}

Is there a way of doing this in F#?


回答1:


As others have pointed out, there is no way to do implicit conversion in F#. However, you could always create your own operator to make it a bit easier to explicitly convert things (and to reuse any op_Implicit definitions that existing classes have defined):

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

Then you can use it like this:

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:


Implicit conversion is rather problematic with respect to type safety and type inference, so the answer is: No, it actually would be a problematic feature.




回答3:


No, there is not.




回答4:


On a related note, it is possible to add implicit or explicit static members so C# can use them.

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

This allows a c# user to use (int) Wales for example




回答5:


You can call the operator like this:

let casted = TargetClass.op_Implicit sourceObject


来源:https://stackoverflow.com/questions/1686895/is-there-an-equivalent-to-creating-a-c-sharp-implicit-operator-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!