私はこのコードを持っています (これはうまくいくと思いますが、失敗します)。理由は本当にわかりません。助けてください
static void Main(string[] args)
{
var x = new MyKeyedCollection();
x.Add(new MyType() { Key = 400L, Value = 0.1 });
x.Add(new MyType() { Key = 200L, Value = 0.1 });
x.Add(new MyType() { Key = 100L, Value = 0.1 });
x.Add(new MyType() { Key = 300L, Value = 0.1 });
//foreach (var item in x)
for (int i = 0; i < x.Count; i++)
{
//Debug.WriteLine(item.PriceLevel);
Debug.WriteLine(x[i].Key);
}
}
}
public class MyType
{
public long Key;
public double Value;
}
public class MyKeyedCollection : KeyedCollection<long, MyType>
{
protected override long GetKeyForItem(MyType item)
{
return item.Key;
}
}
例外:
System.Collections.Generic.KeyNotFoundException は処理
されませんでした Message=指定されたキーはディクショナリに存在しませんでした。
ソース = mscorlib StackTrace: System.Collections.Generic.Dictionary2.get_Item(TKey key) at System.Collections.ObjectModel.KeyedCollection
2の System.ThrowHelper.ThrowKeyNotFoundException() で。 get_Item(TKey キー) で KeyedCollectionTest.Program.Main(String[] args) で ...\Program.cs:line 25 で System.AppDomain._nExecuteAssembly (アセンブリ アセンブリ、String[] 引数) で Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() で System.Threading.ExecutionContext.Run (ExecutionContext executionContext、ContextCallback コールバック、オブジェクト状態) で System.Threading .ThreadHelper.ThreadStart() InnerException:
インデックスではなくキーを取得しようとするのはなぜですか? キーは明らかに長く、int ではありません。以前に KeyedCollection を使用したことは確かですが、長いキーと int インデックスに対しては問題なく機能しました。
ver2、3.5、4、4.5(VS2012使用)でコンパイルしてみました...
それを取得しないでください。