开发者

C#: Executing a Conditional With Object Initializer Syntax

Suppose I have a simple class that Adds:

public class Multiply
{
     public int A {get; set;}
     public int B {get; set;}
     public int C {get; set;}

     public List<int> Res开发者_Python百科ult {get; set;}

     public void Calculate()
     {
         if (A != 0 && B!= 0 && C != 0)
         {
           Result.Add(A);
           Result.Add(B);
           Result.Add(C);
           Result.Add(A * B);
           Result.Add(A * C);
           Result.Add(B * C);
           Result.Add(A * B * C);
         }
     }
}

The above class models my actual application. I have a series of parameters that get set, in this case A, B and C. I then execute Calculate and use the Multiply object's Result property to access the result.

(There might be a better ways to accomplish this template; Lazy loading comes to mind. If you want to suggest a better template go for it but its not the purpose of my question; its just a simple example that illustrates my question.)

Here is my question:

If I'm using the Object Intializer Syntax:

Multiply m = new Multiplier()
{
   A = 1,
   B = 2,
   C = 3
}

m.Calculate();
DoSomething(m.Result[5]); //DoSomething(6); 

Is there a way to execute Calculate() as part of the m initialization?


Make Result a read-only property and move the Calculate logic to it.

But no, you can't call methods with initializer syntax. Then it wouldn't be initializer syntax, it would just be some alternative C# syntax.


Not as far as I know...

But: you could just do the calculation in the getter for Result.

Edit:

Since someone already posted that, you could also just force the arguments to go into your constructor instead of using the initialization block.

This is actually better since you're caching the result. The way your code works, you can change A,B, and C at any time, but the cached value doesn't change. By encapsulating those attributes and only putting them in the constructor, you prevent your object from falling into an inconsistent state, and you can put whatever code you want in the constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜