[英]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. 我希望
A
实现IDictionary<T1,T2>
或能够轻松地将A
用作Dictionary<T1,T2>
。
So far I see two obvious solutions : 到目前为止,我看到了两个明显的解决方案:
Implement explicitly with code such as 使用以下代码明确实现
public int Count { get { return foo.Count();} }
Add an implicit conversion of A
to Dictionary<T1,T2>
, which is more or less enough for my use...for now. 将
A
的隐式转换添加到Dictionary<T1,T2>
,这或多或少足以供我使用...暂时。
I don't like 2 because I want A
to do a little more than foo
. 我不喜欢2,因为我希望
A
做的比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>
. 我显然可以做到1(实际上我做到了),但是实现
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. 不,没有第三种方法:如果希望
A
实例像IDictionary<T1,T2>
一样可用,并且您不希望从Dictionary<T1,T2>
派生您的类,则可以采用两种方法您列出的是您必须使用的。
[I want to] be able to use
A
as aDictionary<T1,T2>
easily.[我希望]能够轻松地将
A
用作Dictionary<T1,T2>
。
Deriving from the dictionary makes sense only when your class A
is indeed a dictionary. 仅当您的
A
类确实是字典时,从字典派生才有意义。 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. 我找到了另一种解决方案,这是一种使用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
. 当我将
IInterface
接口IInterface
到具有已经实现它的字段成员foo
类A
时,它为我提供了通过foo
实现IInterface
的选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.