繁体   English   中英

C#:我可以指定一个类的成员结构作为继承接口的实现者吗?

[英]C#:Can I designate a class' member struct to be the implementer of an inherited interface?

如果我具有实现接口IGetProps的Bag类型的结构,并且我具有一个具有Bag类型的成员变量的Store类,那么我可以在Store的实现中指定我希望Store类通过其bag类型的成员提供IGetProps 。

Bag不能更改为类,这样我就可以继承它。 IGetProps有很多方法,所以我不想用Store中的方法显式地包装每个方法。

例如:

interface IGetProps
{
    int GetA();
    int GetB();
}

struct Bag : IGetProps
{
    public int GetA() { return 0;}
    public int GetB() { return 1;}
    ... // Many more methods
}

class Store : IGetProps
{
    private Bag bag;        // <--- Can I designate bag to be the provide of IGetProps for Store?
}

一个简单的答案是“否”,您的类无法从struct MSDN继承。

结构没有类的继承。 一个结构不能从另一个结构或类继承, 也不能作为一个类的基础 但是,结构是从基类Object继承的。 一个结构体可以实现接口,并且它与类完全一样。

但是,类似的方法可能会起作用,它仍在包装方法,但要尽可能容易地完成。 除此之外,没有其他办法。

interface IGetProps
{
    int GetA();
    int GetB();
}

struct Bag : IGetProps
{
    public int GetA() { return 0; }
    public int GetB() { return 1; }
}

class Store : IGetProps
{
    private Bag bag;        // <--- Can I designate bag to be the provide of IGetProps for Store?

    public int GetA() => bag.GetA(); // <--- c# 6.0 syntax for wrapping a method

    public int GetB() => bag.GetB();
}

我们实现了接口方法,但是接口方法将执行结构GetA()GetB()方法。 当然,我们需要将bag分配给某物(例如,构造变量或属性)。

class Store : IGetProps
{
    public Store(Bag bag)
    {
        this.bag = bag;
    }

    private Bag bag;        // <--- Can I designate bag to be the provide of IGetProps for Store?

    public int GetA() => bag.GetA();

    public int GetB() => bag.GetB();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM