在风格上的差异:IDictionary的VS词典 [英] A difference in style: IDictionary vs Dictionary

查看:161
本文介绍了在风格上的差异:IDictionary的VS词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个朋友,谁是刚刚进入.NET开发的Java开发和年龄,看着他的一些code后后,我发现他做的相当频繁如下:

I have a friend who's just getting into .NET development after developing in Java for ages and, after looking at some of his code I notice that he's doing the following quite often:

IDictionary<string, MyClass> dictionary = new Dictionary<string, MyClass>();

他宣称词典的界面,而不是类。通常情况下我会做到以下几点:

He's declaring dictionary as the Interface rather than the Class. Typically I would do the following:

Dictionary<string, MyClass> dictionary = new Dictionary<string, MyClass>();

在需要时(比如,例如字典传递给接受一个I​​Dictionary接口的方法),我只用IDictionary接口。

I'd only use the IDictionary interface when it's needed (say, for example to pass the dictionary to a method that accepts an IDictionary interface).

我的问题是:有没有什么优点,他的处事方式?这是在Java中的普遍做法?

My question is: are there any merits to his way of doing things? Is this a common practice in Java?

推荐答案

如果IDictionary的是一个更通用的类型而不是字典的话很有道理使用更通用的类型声明变量。这样,你就不必在意尽可能多的有关分配给该变量的实现类,你可以在未来轻易改变的类型,而无需改变很多下列code。例如,在Java中它通常被认为是好做

If IDictionary is a "more generic" type than Dictionary then it makes sense to use the more generic type in declaring variables. That way you don't have to care as much about the implementing class assigned to the variable and you can change the type easily in the future without having to change a lot of following code. For example, in Java it's often considered better to do

List<Integer> intList=new LinkedList<Integer>();

比它做

LinkedList<Integer> intList=new LinkedList<Integer>();

这样,我敢肯定,所有下code对待名单列表,而不是一个LinkedList的,因此很容易在未来的转出的LinkedList的载体或实现List中的任何其他类。我会说这是常见的Java和良好的编程一般。

That way I'm sure all following code treats the list as a List and not a LinkedList, making it easy in the future to switch out LinkedList for Vector or any other class which implements List. I'd say this is common to Java and good programming in general.

这篇关于在风格上的差异:IDictionary的VS词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆