简体   繁体   中英

If I have a class A with a field foo that is a Dictionary, how can I make A implement IDictionary quickly using foo as dataset?

I have the following code :

public class A
{
    Dictionary<T1,T2> foo
    var otherVariable;
    // some other irrelevant code
}

I want A to implement IDictionary<T1,T2> or be able to use A as a Dictionary<T1,T2> easily.

So far I see two obvious solutions :

  1. Implement explicitly with code such as

    public int Count { get { return foo.Count();} }

  2. Add an implicit conversion of A to Dictionary<T1,T2> , which is more or less enough for my use...for now.

I don't like 2 because I want A to do a little more than foo .

I can obviously do 1 (in fact I did it) but it can be a bit lengthy to implement all the methods of IDictionary<T1,T2> .

Is there a third way ?

Is there a third way?

No, there is no third way: if you want instances of A to be usable as if they were an IDictionary<T1,T2> , and you do not wish to derive your class from Dictionary<T1,T2> , then the two ways that you have listed are what you have to work with.

[I want to] be able to use A as a Dictionary<T1,T2> easily.

Deriving from the dictionary makes sense only when your class A is indeed a dictionary. If, on the other hand, it only has a dictionary, without being a dictionary, you may want to use either the conversion operator, or even an appropriately named property for the conversion:

public IDictionary<T1,T2> AsDictionary => foo; // C# 6 syntax

or

public IDictionary<T1,T2> AsDictionary { get { return foo; } } // Legacy C# syntax

I found another solution, an automated way to do what I want with Visual Studio 2015.

When I add the interface IInterface to class A with a field member foo that already implements it, it offers me the option to implement IInterface through foo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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