【问题标题】:Can I assign a type as if it was an int or a string我可以分配一个类型,就好像它是一个 int 或一个字符串
【发布时间】:2021-06-02 04:22:24
【问题描述】:

假设我创建了一个类Number。有没有办法像使用整数或字符串一样分配这种类型的变量?

Number n1 = 123;
Number n2 = "123";

我不介意有一个构造函数来处理这些声明中的任何一个,只要我可以这样写。

【问题讨论】:

    标签: c# declaration


    【解决方案1】:

    您不能为用户定义的类型(例如 Number 类)重载赋值运算符 =。但是,您可以使用构造方法,您可以使用用户定义的转换运算符。看起来像这样:

    public class Number
    {
        private int _actualValue;
    
        public Number(int value) => _actualValue = value;
    
        // User defined conversion operators
        // From int
        public static implicit operator Number(int value)
            => new Number(value);
    
        // From string
        public static implicit operator Number(string value)
        {
            if (!int.TryParse(value, out _actualValue))
            {
                // Invalid format, couldn't parse
                // Throw exception, or set _actualValue = 0
            }
        }
    }
    

    使用它:

    // From int
    Number number = (Number)123;
    
    // From string
    Number number = (Number)"123";
    
    // You can exclude the explicit "(Number)" cast
    

    更多关于用户定义的转换操作在这里:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/user-defined-conversion-operators

    【讨论】:

    • 使用 implicit 运算符,您不再需要 explicit 演员表了。
    • 啊,是的,谢谢。用代码中的注释更新了答案。
    【解决方案2】:

    如果你像这样声明implicit cast operator,你想使用的语法就可以工作:

    public class Number
    {
        public static implicit operator Number(int i) => /* create and return your Number instance */;
    
        //...
    }
    

    现在赋值Number n = 12; 将调用这个操作符。

    但是要小心使用它,它可能会在您没想到时调用运算符时产生副作用。
    只有在没有信息丢失时才应使用隐式转换运算符(因此存在从intdouble 的隐式转换,但只有从doubleint 的显式转换)。

    【讨论】:

    • 你认为你可以给我一个意外调用操作员的例子吗?我自己也想不出来。
    • @Daniel 假设您有两种方法WriteToLog(Number n)WriteToLog(int i)。您可以出于某种原因删除第二个,但您的所有调用(如WriteToLog(12))仍会编译。这当然是一个虚构的例子,我不知道你想用它来做什么。我只是想说可能会有坑。
    猜你喜欢
    • 2016-11-17
    • 1970-01-01
    • 2012-02-14
    • 2020-03-17
    • 2016-05-15
    • 2019-10-19
    • 2017-08-27
    • 2021-03-27
    • 2023-03-14
    相关资源
    最近更新 更多