相关疑难解决方法(0)

非唯一枚举值

我试图掩盖edi文件中的索引位置...我有一种情况,根据情况可以在索引中有2或3个东西.使用枚举隐藏"魔术数字"会很酷,并且很惊讶你可以将多个枚举分配给相同的值,如下所示:

public enum Color
{
    Red = 1,
    Blue = 1,
    Green = 1
}
Run Code Online (Sandbox Code Playgroud)

并且编译器对此很满意.我没想到这会起作用.我不需要回到枚举,所以我不担心回去,但这闻起来很时髦.为什么CLR允许枚举的多个值,我应该使用结构吗?(结构似乎比枚举更重要,这似乎有效)

c# enums struct

51
推荐指数
5
解决办法
2万
查看次数

C# enums - Possible to have double ids

I just noticed that you can create something like this in C#:

enum TestEnum
{
  First = 1,
  Second = 1,
  Third = 2
}

[TestMethod]
public void Test()
{
  TestEnum test = TestEnum.First;
  var en = (TestEnum) 1;//And en is now set to First
}
Run Code Online (Sandbox Code Playgroud)

We would like the enums value to be unique. Right now, I have written a unit test that checks that each value is only used once in our enum. Is there a better way …

.net c# enums unique

5
推荐指数
1
解决办法
480
查看次数

使用Enum.Parse()时出现意外结果

class Program
{
    static void Main(string[] args)
    {
        String value = "Two";
        Type enumType = typeof(Numbers);
        Numbers number = (Numbers)Enum.Parse(enumType, value);
        Console.WriteLine(Enum.Parse(enumType, value));
    }

    public enum Numbers : int
    {
        One,
        Two,
        Three,
        Four,
        FirstValue = 1
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我在应用程序中使用的枚举的简化版本.为什么某些枚举名称没有值的原因是因为我使用其名称作为参数执行Enum.Parse,而具有值的值则从int解析.

如果您单步执行上面的代码并调查'number'变量,您会看到它实际上是'Two',但控制台中的输出是'FirstValue'.此时我看不出原因,是吗?

好的,解决方案很简单 - 只需给无价值的枚举值.但我仍然很好奇.

c# enums parsing

3
推荐指数
1
解决办法
1237
查看次数

标签 统计

c# ×3

enums ×3

.net ×1

parsing ×1

struct ×1

unique ×1