它是声明变量作为接口类型的好/可以接受的做法? [英] Is it a good/acceptable practice to declare variable as interface type?

查看:100
本文介绍了它是声明变量作为接口类型的好/可以接受的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是一个很好的做法使用接口来声明变量?在我的公司,我们有上有一个讨论,我很反对。

Is it a good practice to declare variable using the interface? In my company we had a discussion on it and I'm quite against it.

例如。我想有一个集合存储字符串键和字符串值对。我不希望允许重复无论是。所以很明显我宣布我的字典类变量这将公开曝光(通过属性)。

e.g. I wanted to have a collection storing string keys and string value pairs. I don't want to allow duplicates either. So clearly I declared Dictionary variable in my class which would be exposed publicly (via property).

Dictionary<string, string> myDic;



然而,一个团队成员说,这是不是一个好的做法!他说,你声明一个变量,IDictionary的,这将让消费者指定任何集合(实现IDictionary中),他们希望。例如哈希表或字典

However, a team member says that it's not a good practice ! He is saying that you declare a variable with IDictionary and this will allow consumers to assign any collection (implementing IDictionary) which they want. e.g. Hashtable or Dictionary

IDictionary myDic;
myDic = new Hashtable(); // Consumer's code

mydic =新词典<字符串,字符串>(); //消费者的代码 -

我现在可以知道,是不是真的一个很好的做法来声明变量类型的接口?而这也是我清楚地知道什么是从变量预期?

May I know now, is it really a good practice to declare variable as type of interface? And that too when I clearly know what is expected from that variable?

推荐答案

有关局部变量,私人领域,等它只是分裂毛发。还有就是要定义使用一个接口类型的公共属性受益。例如,我畏缩当我看到暴露类型的属性的类列表<字符串方式>

For local variables, private fields, etc it's just splitting hairs. There is a benefit to defining public properties using an interface type. For example, I cringe when I see a class that exposes a property of type List<string>.

如果您正在使用依赖注入或类似MEF然后使用接口,而不是具体的实现,我们强烈建议组合框架。它使您能够轻松地换出实现与测试实现。

If you're using dependency injection or a composition framework like MEF then using interfaces instead of concrete implementations is highly recommended. It enables you to easily swap out implementations with test implementations.

这篇关于它是声明变量作为接口类型的好/可以接受的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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