无论何时调用Define类中的任何内容,下面的代码似乎都会得到System.TypeInitializationException.这些对保证是不同的,如下所示,并且没有任何代码以任何方式修改词典.然而,每次都会抛出错误ArgumentException: An item with the same key has already been added. Key: Key1.有什么原因会发生这种情况吗?

public static class Define
{
    public static readonly Dictionary<DefineChoices, string> Definitions = new([Pair1, Pair2]);

    public enum DefineChoices
    {
        Key1,
        Key2
    }

    public static readonly KeyValuePair<DefineChoices, string> Pair1 = new(DefineChoices.Key1, "string1");
    public static readonly KeyValuePair<DefineChoices, string> Pair2 = new(DefineChoices.Key2, "string2");

堆栈跟踪如下:

Unhandled exception. System.TypeInitializationException: The type initializer for 'Program.Namespace.Define' threw an exception.
 ---> System.ArgumentException: An item with the same key has already been added. Key: Key1
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at System.Collections.Generic.Dictionary`2.AddRange(IEnumerable`1 enumerable)
   at System.Collections.Generic.Dictionary`2..ctor(IEnumerable`1 collection, IEqualityComparer`1 comparer)
   at System.Collections.Generic.Dictionary`2..ctor(IEnumerable`1 collection)
   at Program.Namespace.Define..cctor() in FilePath\Define.cs:line 2
   --- End of inner exception stack trace ---

推荐答案

初始化静态字段时,初始化顺序很重要.所以,如果你像下面这样安排你的类,它会起作用:

public static class Define
    {
        public static readonly KeyValuePair<DefineChoices, string> Pair1 = new(DefineChoices.Key1, "string1");
        public static readonly KeyValuePair<DefineChoices, string> Pair2 = new(DefineChoices.Key2, "string2");
        public static readonly Dictionary<DefineChoices, string> Definitions = new([Pair1, Pair2]);
        
        public enum DefineChoices
        {
            Key1,
            Key2
        }       
    }

为什么会出现重复键Key1的问题是因为它的默认未初始化值为0.即使您的枚举以1作为起始值,您也会得到一个重复的键值0.

Fiddle

Csharp相关问答推荐

PostingAsJsonAschange在从调用的方法返回时给出500错误

Plotly.NET访问互联网时出现异常

在C#中使用in修饰符

SignalR客户端不会打印队列位置'

选取器与.NET Maui MVVM的绑定属性

Nuget包Serilog.Sinks.AwsCloudwatch引发TypeLoadExceptions,因为父类型是密封的

Rx.Net窗口内部可观测数据提前完成

当前的文化决定了错误的文化

TeamsBot SendActivityActivityTypes与ActivityTypes同步.键入不再起作用

如何让NLog停止写入冗余信息?

如何在NET 8最小API中自动记录TypedResults.Stream响应

在C#中,非静态接口方法的抽象和虚拟是冗余的吗?

正在try 从Blazor中的API读取JSON

Blazor:搜索框在第一次搜索时不搜索

RCL在毛伊岛应用程序和Blazor服务器应用程序.Net 8.0中使用页面

在.NET Maui中,Flyoutindow/Hamburger菜单可以在shell 之外实现吗?

如何解决System.StackOverflowException:抛出System.StackOverflowException类型的异常.&# 39;生成随机代码时发生异常?

Autofac -动态实例化:手动传递构造函数

如何使用LINQ在C#中填充列表列表?

默认架构不存在EF核心迁移