Jes*_*per 6 c# dependencies dependency-injection
有人可以给我一个隐藏依赖的例子.我用谷歌搜索了它,发现了这样的结果:
"可见依赖项是开发人员可以从类的接口看到的依赖项.如果从类的接口中看不到依赖项,则它是隐藏的依赖项."
(来源 - http://tutorials.jenkov.com/ood/understanding-dependencies.html#visiblehidden)
但我还是不太明白.
是否在函数内部发生依赖,而不是在类的开头发生声明的变量?或者,当您只是创建除接口中声明的签名方法之外的函数时?
Dav*_*son 10
以下是隐藏依赖项的示例:
class Foo
{
void doSomething() //a visible method signature
{
//the body of this method is an implementation detail
//and is thus hidden
new Bar().doSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
在上述例子中,Bar是一个依赖于Foo因为Foo依赖的协作Bar.
它是隐藏的,因为依赖关系在Bar构造函数Foo或方法签名中不是显式的Foo.
将类视为定义暴露给协作者的可见合同.方法和构造函数签名是该合同的一部分.方法的主体doSomething()是隐藏的,因为它是类中未在合同中公开的内部实现细节.我们从签名中得到的所有信息都是有一种叫做doSomething()返回类型的方法void.
对于反例,我们可以重构类以使依赖项显示:
class Foo
{
private readonly Bar bar;
Foo(Bar bar) //the constructor signature is visible
{
this.bar = bar;
}
void doSomething()
{
bar.doSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,Bar显式定义为构造函数的公开签名中的依赖项.
或者我们可以这样做:
class Foo
{
void doSomething(Bar bar) //method signature is visible
{
bar.doSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
现在,Bar方法的依赖性doSomething是可见的,因为它包含在方法签名中doSomething.
| 归档时间: |
|
| 查看次数: |
775 次 |
| 最近记录: |