简体   繁体   English

在C#中使用枚举进行数学运算(例如DayOfWeek)

[英]Math with Enums (e.g. DayOfWeek) in C#

Why is it that the following code won't work: 为什么以下代码不起作用:

endDate.AddDays(7-endDate.DayOfWeek);

While this will: 虽然这将:

endDate.AddDays(0-endDate.DayOfWeek + 7);

?

(By "won't work" I mean results in the following compilation error: "cannot convert from 'System.DayOfWeek' to 'double'") (通过“不起作用”,我的意思是导致以下编译错误:“无法从'System.DayOfWeek'转换为'double'”)

To expand upon what Lasse said (or rather, make it a little more explicit). 扩展Lasse所说的内容(或者更明确一些)。

Because 0 is convertable to an Enum type, 由于0可转换为Enum类型,

0 - endDate.DayOfWeek becomes 
(DayOfWeek)0 - endDate.DayOfWeek

And since you can subtract one enum from another and get an integer difference: 并且由于您可以从另一个枚举中减去一个枚举并获得整数差值:

(DayOfWeek)0 - endDate.DayOfWeek == (int)endDate.DayOfWeek

Thus, since the result of the subtraction is an int, you can then add 7 to it. 因此,由于减法的结果是整数,因此可以将其加7。

endDate.AddDays(0-endDate.DayOfWeek + 7);

So, if Monday's Enum value is 1 因此,如果星期一的Enum值为1

0 - endDate.DayOfWeek == -1 + 7 == 6

However, you can't do the reverse. 但是,您不能相反。

endDate.DayOfWeek - 0 + 7, 

because the result type of the calculation is dependant upon the leftmost side. 因为计算的结果类型取决于最左侧。 Thus, while 0 - endDate.DayOfWeek results in an integer, endDate.DayOfWeek - 0 results in an enum DayOfWeek. 因此,虽然0-endDate.DayOfWeek产生整数,但endDate.DayOfWeek-0产生枚举DayOfWeek。

Most interestingly, you could use this side-effect to get the value of an enum without casting, though I would consider this hackish and confusing... thus to be avoided. 最有趣的是,您可以使用这种副作用来获取枚举的值而无需强制转换,尽管我会认为这种hacky和令人困惑的地方……因此可以避免。

int enumValue = -(0 - endDate.DayOfWeek);

This is very interesting. 这很有趣。 The right way to do this is: 正确的方法是:

endDate.AddDays(7 - (int)endDate.DayOfWeek);

But, your question isn't about a solution, but a reason for the behavior. 但是,您的问题不是解决方案,而是行为的原因。 It has something to do with the way the compiler treats a zero. 它与编译器对待零的方式有关。 Either line fails if no zero is present, while both lines work if a zero is present. 如果不存在零,则任何一条线都将失败,而如果存在零,则两条线都将起作用。

You can subtract two enum values to get their integer value difference: 您可以减去两个枚举值以获得其整数值差:

using System;

namespace ConsoleApplication10
{
    public enum X { A, B, C, D }
    public class Program
    {
        static void Main()
        {
            var x = X.D + X.A;
            Console.Out.WriteLine(x);
            Console.In.ReadLine();
        }
    }
}

Will print out 3. 将打印输出3。

But you can't add, probably makes no sense. 但是您不能添加,可能没有任何意义。

In the case of "0", 0 is auto-convertible to all enum types, so basically "0 - enumvalue" means the same as "(enumtype)0 - enumvalue", which again works. 在“ 0”的情况下,0可以自动转换为所有枚举类型,因此基本上“ 0-枚举值”的含义与“(enumtype)0-枚举值”相同,这再次起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM