如何重写下面的代码,使我不会';在只由构造函数调用的方法中,不必分配只读变量

本文关键字:函数调用 只读 变量 分配 不必 方法 重写 何重写 代码 | 更新日期: 2023-09-27 18:06:12

例如

        Class A
          {
           readonly Bclass B;
           readonly Cclass C;
           public void Class()
               {
                 Action1();
                 Action2();
                 Action3();
               }
           void Action2()
              {
                Dosomething1();
                B=Dosomething2(); //There goes the problem.
                C=Dosomething3();
                Dosomething4();
              }
           ...
          }

顺便说一句,我知道我可以把所有的Dosomthing((放入构造函数中,但代码因此变得可读性较差。

如何重写下面的代码,使我不会';在只由构造函数调用的方法中,不必分配只读变量

您可以重构A,使B作为一个只有setter的属性公开:

public class A
{
    public A() 
    {
        _b = DoSomething();
    }
    private BClass MyClassB
    {
        get { return _b; }
    }
    private BClass _b;
}

您还可以做其他一些事情,但很难确切地了解使用Breadonly实例的问题所在。它将通过这种方式使其不可变——一旦在构造函数中设置了它,就不能在类中的任何其他地方进行更改——请注意,如果使用上面说明的属性i,就会失去不变性。

    Class A
      {
       readonly Bclass B;
       readonly Cclass C;
       public void Class()
           {
             Action1();
             Tuple<B,C> init = Action2();
             B = init.B;
             C = init.C;
             Action3();
           }
      }

不幸的是,C#缺乏元组支持,因此您无法编写

B, C = Action2();