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

cbp*_*cbp 14 c# struct typeconverter

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

Unit myUnit = 5;
Run Code Online (Sandbox Code Playgroud)

而不是必须这样做:

Unit myUnit = new Unit(5);
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ell 31

您需要提供从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; }
    }
Run Code Online (Sandbox Code Playgroud)