是否有一个相当于创造了F#C#的隐式运算符? [英] Is there an equivalent to creating a C# implicit operator in F#?

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

问题描述

在C#中,我可以添加隐含的经营者一类,如下所示:

 公共类MyClass的
{
私人int数据;

公共静态隐运营商MyClass的(int i)以
{
返回新MyClass的{数据= I};
}

公共静态隐运营商MyClass的(字符串s)
{
INT结果;

如果(int.TryParse(S,出结果))
{
返回新MyClass的{数据=结果};
}
,否则
{
返回新MyClass的数据{= 999};
}
}

公共重写字符串的ToString()
{
返回data.ToString();
}
}



然后我可以传递期待一个MyClass的任何功能对象的字符串或int。
例如:

 公共静态字符串获取(MyClass的C)
{
返回c.ToString ();
}

静态无效的主要(字串[] args)
{
串S1 = GET(21);
字符串s2 = GET(你好);
串S3 = GET(23);
}

有F#中这样做的方法吗?


解决方案

正如其他人所指出的那样,没有办法做到在F#中隐式转换。但是,你总是可以创建自己的运营商,使其更容易一点明确转换的事情(和重用现有的类定义的任何op_Implicit定义):





<预类=郎毫升prettyprint-覆盖> 让内联(大于!)(X:^一):^ b =((^ A或^ b):(静态成员op_Implicit:^一 - > ^ b)x)的

然后你可以使用它像这样:



<预类=郎毫升prettyprint-覆盖> A型()=级终端
型b()=静态成员op_Implicit (A:A)= b()

让myfn(b:b)=结果

(*应用隐式转换到A使用我们的运营商,然后调用函数*)
myfn(大于!A())


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#?

解决方案

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天全站免登陆