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. If your collection doesn't expose members to iterate over keys (like Dictionary
exposes Keys
) then this is your only option. By the way, may be you collection is IEnumerable
? Actually it is strange for a collection not to provide any iteration facilities. Is not it called YouCanOnlyUseIndexCollection
?
精彩评论