C# : How does this work : Unit myUnit = 5;

标签 c# struct typeconverter

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

Unit myUnit = 5;

不必这样做:

Unit myUnit = new Unit(5);

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

最佳答案

您需要提供一个从 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; }
    }

关于C# : How does this work : Unit myUnit = 5;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/200858/

相关文章:

c# - protected 内部

c# - .NET 核心 3.1 : Ignore expired SSL certficate

c# - 从顺序文件读取到结构数组

C++ - 无法将 CSV 解析到我的结构中

php - 类、封装和用户输入

android - 如何在TypeConverter中使用Gson将Kotlin枚举与Room存储在一起?

c# - Paypal 返回 URL 未正确触发

c# - 使用 List<string>、Autofixture 创建测试数据

struct - 有没有一种优雅的方法可以在没有 PhantomData 的情况下使用未使用的类型制作通用元组结构?

c# - 日期时间类型转换器