C#为什么不带枚举= 1 [英] c# why not taking enum=1

查看:90
本文介绍了C#为什么不带枚举= 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Query3
{
    enum Foo
    {
        mon,
        tue
    };

    static void Main()
    {
        Foo f =1;       
        Console.WriteLine(f);
        Console.ReadLine();
    }
}



你好,
我想知道为什么"Foo f = 1"给出错误.
请帮忙.....

在此先感谢...



Hello,
I want to know, why "Foo f=1" is giving Error.
please help.....

Thanks in advance...

推荐答案

简短的回答,即使Foo的值为1,1也不是Foo类型. VB开发人员有机会吗?我说这是.net的枚举是基于.net的原因,所以tue是1,而不是mon(它是0),但是我离题了.修复代码很简单:

Short answer, 1 isn''t of type Foo even though Foo has a value of 1. You aren''t a VB dev by any chance? The reason I say this is the enum is 0-based in .net so tue is 1, not mon (which is 0), but I digress. To fix your code is simple:

Foo f =(Foo)1;  




尽管在许多情况下上述方法很有用,但更常见的做法是




Though there are lots of circumstances where the above is useful, it is more usual to do

Foo f =Foo.tue;


因为您没有将int强制转换为枚举.首先需要像这样铸造它
Because you didnt cast int to enum. What you need to do first is cast it, like this
Foo f = (Foo)1; 


但是,这将给您两个,因为枚举基于零.因此,您可能希望像这样修改您的代码.


This however, will give you two because enums are zero based. So you might want to modify your code like this.

enum Foo
{
    mon=1,
    tue=2
};


您不能直接为enum分配整数值.看这个技巧.它显示了一种将枚举变量分配给整数的更好方法.

从有问题的数据源(对于C#和VB)设置枚举器 [ ^ ]
You can''t directly assign an enum an integer value. Look at this tip. It shows a better way to assign an enum variable to an integer.

Setting Enumerators From Questionable Data Sources (for C# and VB)[^]


这篇关于C#为什么不带枚举= 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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