所以,我在以下结构上写了两个接口:
public interface IBar
{
string DoStuff();
}
public interface IFoo
{
IBar Bar { get; set; }
}
在IFoo
的实施中,我必须做以下事情:
public class FooImpl : IFoo
{
private BarImpl _barImpl;
public IBar Bar
{
get { return _barImpl }
set { _barImpl = (BarImpl) value }
}
}
然后我总是必须在使用它时抛出一些东西,除非我管理一些我不想要的隐式运算符。
那么,是否有更好的方法来编写这个以便不对其进行处理,并且可能在我的实现上有一个干净的Property { get; set; }
?
修改
只是为了澄清为什么我(想)我需要这样:让我们说FooImpl
我需要BarImpl
的特定方法来处理。但DoStuff()
可以从IBars
等其他地方调用所有fooImpl.Bar.DoStuff()
共有的lib
。这有意义吗?
谢谢!
答案 0 :(得分:2)
如何使用通用接口?试试这段代码:
public interface IFoo<T> where T : IBar
{
T Bar { get; set; }
}
public class FooImpl : IFoo<BarImpl>
{
private BarImpl _barImpl;
public BarImpl Bar
{
get { return _barImpl; }
set { _barImpl = value; }
}
}
答案 1 :(得分:1)
你可以在那里使用一个构造函数,该构造函数接受IBar
类型参数的对象,并从类外部传递BarImpl
,这将为它添加松散耦合,如:
public class FooImpl : IFoo
{
private IBar _barImpl;
public IBar Bar
{
get { return _barImpl }
set { _barImpl = value; }
}
public FooImpl(IBar bar)
{
_barImpl = bar;
}
}
在这种情况下,您可能希望将IBar
属性设为只读,以便无法从外部进行更改,因此只需在其中添加getter:
public IBar Bar
{
get { return _barImpl; }
}
这样你的FooImpl
只知道接口,并没有与IBar
的实现紧密绑定,任何实现都可以从外部传递。
现在,在创建FooImpl
的实例时,您必须将BarImpl
作为参数传递:
BarImpl bar = new BarImpl();
var foo = new FooImpl(bar);
希望它有所帮助!
答案 2 :(得分:1)
我认为你以错误的方式接近Interfaces的概念。绝对值IFoo
不应该要求IBar
的具体实现。在IFoo
实施中,删除对BarImpl
的任何引用,并将其替换为IBar
。
如果由于一个特殊原因,FooImpl
只能与BarImpl
一起使用,而没有其他实现,那么在您的IoC注册中就可以这样设置。如果我不知道您正在使用哪个IoC容器,则无法指导您完成此操作。如果您根本不使用IoC,那么您当然可以实例化IBar
的正确类型。
答案 3 :(得分:0)
一种选择是使用explicit interface implementation:
public class FooImpl : IFoo
{
private BarImpl _barImpl;
public BarImpl Bar
{
get { return _barImpl; }
set { _barImpl = value; }
}
IBar IFoo.Bar
{
get { return _barImpl; }
set { _barImpl = (BarImpl)value; }
}
}
在这种情况下,只要您使用FooImpl
类型的对象,Bar
属性就会返回BarImpl
类型,无需将其强制转换为调用代码。但是,该类仍然正确实现IFoo
,并将在用作IBar
引用的任何上下文中返回IFoo
引用。
如果您可以将IFoo.Bar
更改为只读,而不是要求IFoo
实施者通过构造函数或其他方式获取其IBar
成员,则此实现会变得更加清晰。这允许FooImpl
要求BarImpl
IBar
IFoo.Bar
的实施,而无需在<div class="owl-carousel owl-theme">
@foreach(var m in Model) {
<div class="item-box item">
@Html.Partial("_ProductBox", m)
</div>
}
</div>
<script type="text/javascript">
$(document).ready(function() {
var owl = $('.owl-carousel');
owl.owlCarousel({
items: 3,
loop: true,
margin: 10,
autoplay: true,
autoplayTimeout: 1000,
autoplayHoverPause: true
});
})
</script>
设置者中进行投射。