我为什么要投枚举在C#中为int? [英] Why do I have to cast enums to int in C#?

查看:148
本文介绍了我为什么要投枚举在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;
    }
}



反正是有防止铸件?

Is there anyway to prevent the casting?

推荐答案

排序 - 投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天全站免登陆