KeyedCollection与枚举密钥类型不会指数INT [英] KeyedCollection with enum key type will not index by int
问题描述
我上课
public class FooKeyedCollection : KeyedCollection<FooType,Foo>
{
}
public enum FooType
{
FooType1,
FooType2,
FooType3
}
public Foo
{
public FooType Type { get; set; }
public string Value { get; set; }
}
当我将项目添加到我的FooKeyedCollection,我还可对其进行索引由FooType,但是当我试图索引他们诠释,int是ptted作为FooType枚举除$ P $。其结果是,它会导致混乱的错误,即
When I add items to my FooKeyedCollection, I can index them by FooType, but when I attempt to index them int, the int is interpretted as the FooType enum. As a result, it leads to a confusing error, i.e.
public static void main()
{
FooKeyedCollection fkc = new FooKeyedCollection();
Foo myFoo = new Foo();
myFoo.Type = FooType.FooType3;
myFoo.Value = "someValue";
foo.Add( myFoo );
Foo myFooByType = foo[FooType.FooType3];
Foo myFooByIndex = foo[0]; // <-- exception thrown here
}
在执行此code的结果是试图通过整数索引检索项目时异常。我希望到FooKeyedCollection公开为公共API的一部分,我要保护这个API的消费者从这一错误。有没有什么办法,我可以修改FooKeyedCollection类来获得正确的行为?
The result of executing this code is an exception when attempting to retrieve the item by integer index. I hope to expose the FooKeyedCollection as part of a public API, and I want to protect the consumers of this API from this error. Is there any way that I can modify the FooKeyedCollection class to get proper behavior?
推荐答案
您可以考虑使用新关键字的位置:
You might consider using the "new" keyword here:
public new Foo this[int index]
{
get
{
IList<Foo> self = this;
return self[index];
}
set
{
(IList<Foo>)[index] = value;
}
}
这将允许您指数整数值。使用枚举明确将回落到KeyedCollection实施。
This will allow you to index by integer value. Using the enum explicitly will fall back to the KeyedCollection implementation.
这篇关于KeyedCollection与枚举密钥类型不会指数INT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!