无论何时调用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 ---