是否有等效于在 F# 中创建 C# 隐式运算符的方法? [英] Is there an equivalent to creating a C# implicit operator in F#?

查看:18
本文介绍了是否有等效于在 F# 中创建 C# 隐式运算符的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

然后我可以将任何需要 MyClass 对象的函数传递给字符串或整数.例如

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

有没有办法在 F# 中做到这一点?

Is there a way of doing this in F#?

推荐答案

正如其他人所指出的,在 F# 中没有办法进行隐式转换.但是,您始终可以创建自己的运算符,以便更轻松地显式转换事物(并重用现有类已定义的任何 op_Implicit 定义):

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

这篇关于是否有等效于在 F# 中创建 C# 隐式运算符的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆