简体   繁体   English

如何发现C#索引器中使用的键?

[英]How can I discover the keys used in a C# indexer?

We have a legacy class that uses an indexer to allow people to add arbitrary key-value pairs: 我们有一个旧类,该类使用索引器来允许人们添加任意键/值对:

legacyInstance["myKey"] = value;

Sadly, we can't look at or modify the code for this class. 可悲的是,我们无法查看或修改此类的代码。 We can only access it through its various properties. 我们只能通过其各种属性来访问它。

What we need to do is clone this object in an intelligent way. 我们需要做的是以一种智能的方式克隆该对象。 Normal properties are simple to clone, of course: 普通属性很容易克隆,当然:

myClone.blargle = legacyInstance.blargle;

But how do we discover all of the keys that someone may have added to a particular object instance in order to clone them correctly? 但是,我们如何发现某个人可能已添加到特定对象实例的所有键,以便正确克隆它们? Ideally something like this: 理想情况是这样的:

string[] keys = legacyInstance.<#magic!#>;
foreach (string key in keys)
{
    myClone[key] = legacyInstance[key];
}

And while I suspect the magic may involve some Reflection, getting at it is proving difficult since I am a Reflection tyro. 虽然我怀疑魔术可能涉及反射,但事实证明,由于我是反射型陀螺仪,很难做到这一点。

Grab the ILSpy and get into sources. 抓住ILSpy并获取源代码。 If your collection doesn't expose members to iterate over keys (like Dictionary exposes Keys ) then this is your only option. 如果您的集合没有让成员迭代键(例如Dictionary暴露Keys ),那么这是您唯一的选择。 By the way, may be you collection is IEnumerable ? 顺便说一句,可能您的收藏是IEnumerable吗? Actually it is strange for a collection not to provide any iteration facilities. 实际上,对于集合不提供任何迭代功能是很奇怪的。 Is not it called YouCanOnlyUseIndexCollection ? 它不是叫做YouCanOnlyUseIndexCollection吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM