C#:这是如何工作的:单位myUnit = 5;

时间:2022-11-10 14:28:12

I just noticed that you can do this in C#:

我刚刚注意到你可以在C#中做到这一点:

Unit myUnit = 5;

instead of having to do this:

而不是必须这样做:

Unit myUnit = new Unit(5);

Does anyone know how I can achieve this with my own structs? I had a look at the Unit struct with reflector and noticed the TypeConverter attribute was being used, but after I created a custom TypeConverter for my struct I still couldn't get the compiler to allow this convenient syntax.

有谁知道我如何用自己的结构实现这一目标?我看了一下带有反射器的Unit结构,注意到正在使用TypeConverter属性,但是在为我的struct创建了一个自定义的TypeConverter后,我仍然无法让编译器允许这种方便的语法。

2 个解决方案

#1


31  

You need to provide an implicit conversion operator from int to Unit, like so:

您需要提供从int到Unit的隐式转换运算符,如下所示:

    public struct Unit
    {   // the conversion operator...
        public static implicit operator Unit(int value)
        {
            return new Unit(value);
        }
        // the boring stuff...
        private readonly int value;
        public int Value { get { return value; } }
        public Unit(int value) { this.value = value; }
    }

#2


2  

You need to provide a cast operator for the class that takes an Int32.

您需要为采用Int32的类提供强制转换运算符。

#1


31  

You need to provide an implicit conversion operator from int to Unit, like so:

您需要提供从int到Unit的隐式转换运算符,如下所示:

    public struct Unit
    {   // the conversion operator...
        public static implicit operator Unit(int value)
        {
            return new Unit(value);
        }
        // the boring stuff...
        private readonly int value;
        public int Value { get { return value; } }
        public Unit(int value) { this.value = value; }
    }

#2


2  

You need to provide a cast operator for the class that takes an Int32.

您需要为采用Int32的类提供强制转换运算符。