客户枚举类型和系统枚举类型之间是否有任何区别

时间:2011-07-19 04:47:07

标签: c#

我做了如下↓

之类的测试

1)创建一个客户枚举(从一周开始复制)

[Serializable]
public enum Tester
{
    // 概要:
    //     Indicates Sunday.
    Sunday = 0,
    //
    // 概要:
    //     Indicates Monday.
    Monday = 1,
    //
    // 概要:
    //     Indicates Tuesday.
    Tuesday = 2,
    //
    // 概要:
    //     Indicates Wednesday.
    Wednesday = 3,
    //
    // 概要:
    //     Indicates Thursday.
    Thursday = 4,
    //
    // 概要:
    //     Indicates Friday.
    Friday = 5,
    //
    // 概要:
    //     Indicates Saturday.
    Saturday = 6,
}

2)创建两种测试方法......

    static void TestEnumToString()
    {
        var t = Tester.Sunday;
        Enumerable.Range(0, 1000000).ToList().ForEach(i => t.ToString());
    }

    static void DayOfWeekEnumToString()
    {
        var t = DayOfWeek.Sunday;
        Enumerable.Range(0, 1000000).ToList().ForEach(i => t.ToString());
    }

3)主要方法

    static void Main()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        TestEnumToString();
        sw.Stop();
        Console.WriteLine("Tester:" + sw.ElapsedMilliseconds);


        sw = new Stopwatch();
        sw.Start();
        DayOfWeekEnumToString();
        sw.Stop();
        Console.WriteLine("DayOfWeek:" + sw.ElapsedMilliseconds);

        Console.ReadKey();
    }

4)结果:

Tester : 3164ms
DayOfWeek : 7032ms

我真的不知道为什么系统类型枚举比客户枚举类型慢.... 谁能告诉我为什么? 谢谢......

更新编辑: 将[ComVisible(true)]添加到枚举。

[ComVisible(true)]
[Serializable]
public enum Tester
{
    Sunday = 0,


    Monday = 1,


    Tuesday = 2,


    Wednesday = 3,


    Thursday = 4,


    Friday = 5,


    Saturday = 6,
}

结果:

Tester : 5018ms
DayOfWeek : 7032ms

系统枚举类型仍然比客户枚举类型慢......

2 个答案:

答案 0 :(得分:1)

如果要将苹果与苹果进行比较,则应添加[ComVisible(true)]属性。

答案 1 :(得分:1)

Enum可以使用[ComVisible(true)]或[Flags]进行装饰,每次更改测试结果时都可以。

[Serializable]
//[Flags]
[ComVisible(true)]
public enum Tester
{    
  // 概要:
  //     Indicates Sunday.
  Sunday = 0,