C# - 接口设置属性为{get,set}另一个接口

时间:2017-08-21 18:09:30

标签: c# interface

所以,我在以下结构上写了两个接口:

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。这有意义吗?

谢谢!

4 个答案:

答案 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> 设置者中进行投射。