14

我刚刚注意到您可以在 C# 中执行此操作:

Unit myUnit = 5;

而不必这样做:

Unit myUnit = new Unit(5);

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

4

2 回答 2

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; }
    }
于 2008-10-14T12:06:10.090 回答
2

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

于 2008-10-14T12:02:01.380 回答