为什么我必须在C#中将枚举转换为int? [英] Why do I have to cast enums to int in C#?

查看:1255
本文介绍了为什么我必须在C#中将枚举转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

internal enum WindowsMessagesFlags {
    WM_EXITSIZEMOVE      = 0x00000232,
    WM_DISPLAYCHANGE     = 0x0000007e,
    WM_MOVING            = 0x00000216,
}

protected override void WndProc(ref Message m) {
    switch(m.Msg) {
        case (int)WindowsMessagesFlags.WM_DISPLAYCHANGE:
            FixWindowSnapping();
            break;
        case (int)WindowsMessagesFlags.WM_EXITSIZEMOVE:
            SaveWindowProperties();
            break;
        case (int)WindowsMessagesFlags.WM_MOVING:
            KeepProperLocation(ref m);
            break;
    }
}

是否还有防止投放?

推荐答案

排序 - 投放m.Msg:

Sort of - cast m.Msg instead:

protected override void WndProc(ref Message m) {
    switch((WindowsMessagesFlags) m.Msg) {
        case WindowsMessagesFlags.WM_DISPLAYCHANGE:
                FixWindowSnapping();
                break;
        case WindowsMessagesFlags.WM_EXITSIZEMOVE:
                SaveWindowProperties();
                break;
        case WindowsMessagesFlags.WM_MOVING:
                KeepProperLocation(ref m);
                break;
    }
}

C#枚举不仅仅是数字 - 它们是与类型相关联的数字。这会阻止您执行(不转换):

The reason you need the cast at all is because in C# enums aren't just numbers - they're numbers associated with the type. This prevents you from doing (without casting):

HttpStatusCode status = someWindowsMessageFlag;

这显然是一件好事:)当你需要的时候, 底层类型(在这种情况下为int)。

This is clearly a good thing :) When you need to, however, you can always go "via" the underlying type (int in this case).

这篇关于为什么我必须在C#中将枚举转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆