加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 用户定义的struct转换为函数的默认参数

发布时间:2020-12-15 21:56:19 所属栏目:百科 来源:网络整理
导读:public struct MyInt{ public int csInt; public MyInt(int i) { csInt = i; } public MyInt(double d) { csInt = (int)d; } public static implicit operator MyInt(int value) { return new MyInt(value); } public static implicit operator MyInt(double
public struct MyInt
{
    public int csInt;

    public MyInt(int i)
    {
        csInt = i;
    }

    public MyInt(double d)
    {
        csInt = (int)d;
    }

    public static implicit operator MyInt(int value)
    {
        return new MyInt(value);
    }

    public static implicit operator MyInt(double value)
    {
        return new MyInt(value);
    }
}


int MyFunc(MyInt i = 0)
{
    return -1;
}

我想实现一个包装器structMyInt(在这里简化)接受int作为默认值(我知道这很奇怪和不自然,我只需要它遵守其他语言格式),但我遇到错误,当我像上面的代码,错误是at int MyFunc(MyInt i = 0)其中VS2012说:

a value of type ‘int’ cannot be used as a default parameter because there are no standard conversions to Type MyInt

据我所知,int和double也在C#中定义为struct.所以我试过以下:

int MyFunc(double i = (int)0)
{
return -1;
}

它过去了!因此我认为默认参数允许类型转换.

所以我的问题是:

>为什么不能将MyInt的隐式类型转换用作默认para?
>标准转换在VS错误消息中的含义是什么,它是否来自MyInt中定义的隐式转换?

解决方法

隐式转换运算符是方法,您不能使用方法(或事件静态字段)作为默认参数 – 只允许使用常量(这是有道理的,因为编译器实际上会在您调用方法的任何地方使用这些常量.)

在您的情况下,由于您需要struct的默认值(即所有字段初始化为0),您可以使用default关键字:

int MyFunc(MyInt i = default(MyInt))
{
    return -1;
}

C#标准转换是编译器可以自己执行的转换(如Int32到Double或任何类型到Object).您可以在C# Specification中阅读所有相关信息.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读