how to rewrite the following code so that i don't have to assign readonly variable in a method only called by constructor?
e.g
Class A
{
readonly Bclass B;
readonly Cclass C;
public void Class()
{开发者_JAVA百科
Action1();
Action2();
Action3();
}
void Action2()
{
Dosomething1();
B=Dosomething2(); //There goes the problem.
C=Dosomething3();
Dosomething4();
}
...
}
BTW, i know i can put all the Dosomthing() into the constructor, but the code hence becomes less readable.
You could refactor A
so that B
is exposed as a property with only a setter:
public class A
{
public A()
{
_b = DoSomething();
}
private BClass MyClassB
{
get { return _b; }
}
private BClass _b;
}
There are a couple of other things you could potentially do, but it is hard to see exactly what your problem is with using a readonly
instance of B
. It will be done this way to make it immutable - once it has been set in the constructor it cannot be changed anywhere else in the class - note that you lose the immutability if you use the property i illustrated above.
Class A
{
readonly Bclass B;
readonly Cclass C;
public void Class()
{
Action1();
Tuple<B,C> init = Action2();
B = init.B;
C = init.C;
Action3();
}
}
Unfortunately, C# lacks tuple support, so you cannot write
B, C = Action2();
精彩评论