嵌套的类和接口

所以我在设计某些东西时遇到了问题。本质上,我有一个类A,它由类型为B的对象的数组组成。我只希望公开类A的接口,并希望对任何用户基本上都隐藏类B。我希望能够对类型B及其数据执行操作,但只能通过类A的B实例的接口/方法调用方法来进行操作。棘手的部分是我想创建一个对成员执行操作的方法类型B,但我想实现一个接口,然后有一个实现该接口的类,因为我希望我的用户能够创建自己的此方法的实现。我当时想像这样做somtehing:


public class A 

{

    B[] arr;

    C c;


    public A(C c) 

    { 

        arr = new B[100];

        this.c = c;

    }



    public void method1() 

    {

        var b = new B();

        b.someMethodofb(c);    // pass c to the method of b

    }


    private class B 

    {

        someMethodOfb(C c) 

        {

        }

    }

}


public class C : Interface1 

{

    public void method(B b) 

    {    

        //interface method we have implemented

    }

}

我将B类设为私有,是因为我只希望A类可以公开使用,所以发生在B类上的所有事情都会通过A类发生,这也是为什么我将B嵌套在A中的原因。但是由于B类是私有的,我可以用它作为我的C类方法的参数?实现Interface1的方法将影响B如何执行someMethodOfb的内部实现,这就是为什么我认为我需要传递它以保持类B的隐藏特性的原因。请问有没有更好的方法让我设计此功能并能够实现我在第一段中设定的目标?


qq_笑_17
浏览 142回答 2
2回答

30秒到达战场

让我们用具体的例子:)说,我们有三个类:Customer,Order和OrderProcessor。客户和订单是分别代表客户和订单的实体,而OrderProcessor将处理订单:public interface IOrderProcessor{&nbsp; &nbsp; void ProcessOrder(IOrder order);}public interface IOrder{&nbsp; &nbsp; void FinalizeSelf(IOrderProcessor oProc);&nbsp; &nbsp; int CustomerId {get; set;}}public class Customer{&nbsp; &nbsp; List<IOrder> _orders;&nbsp; &nbsp; IOrderProcessor _oProc;&nbsp; &nbsp; int _id;&nbsp; &nbsp; public Customer(IOrderProcessor oProc, int CustId)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _oProc = oProc;&nbsp; &nbsp; &nbsp; &nbsp; _orders = new List<IOrder>();&nbsp; &nbsp; &nbsp; &nbsp; _id = CustId;&nbsp; &nbsp; }&nbsp; &nbsp; public void CreateNewOrder()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; IOrder _order = new Order() { CustomerId = _id };&nbsp; &nbsp; &nbsp; &nbsp; _order.FinalizeSelf(_oProc);&nbsp; &nbsp; &nbsp; &nbsp; _orders.Add(_order);&nbsp; &nbsp; }&nbsp; &nbsp; private class Order : IOrder&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public int CustomerId {get; set;}&nbsp; &nbsp; &nbsp; &nbsp; public void FinalizeSelf(IOrderProcessor oProcessor)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; oProcessor.ProcessOrder(this);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}public class ConcreteProcessor : IOrderProcessor{&nbsp; &nbsp; public void ProcessOrder(IOrder order)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //Do something&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP