如何确保所有类字段在首次使用之前都已初始化 [英] How to ensure all class fields have been initialized before first use

查看:70
本文介绍了如何确保所有类字段在首次使用之前都已初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个可以进行一些计算的类.这组计算需要输入一组参数.

let's say I have a class that does some calculations. This set of calculations requires as an input a set of parameters.

public class Calculator
{
private CalculatorConfig _config;
public Calculator(CalculatorConfig config)
{
_config = config;
}

public Result Calculate(object obj){}
}

我的CalculatorConfig类非常简单:

My CalculatorConfig class is very simple :

public class CalculatorConfig
{
      public double param1;
      public double param2;
      ...
}

我非常简单地初始化它

var config = new CalculatorConfig();
config.param1 = val;
....
var calculator = new Calculator(config);

我遇到的难题是,此类的用户可能会忘记初始化一些可能导致奇怪行为的字段. 可能有意义的解决方案是将字段转换为属性,并且对于每个私有字段,都有一个额外的布尔值,该布尔值将保存有关字段是否已初始化的信息. 我还可以创建一个大型构造函数,该构造函数会将所有字段作为参数.

The dilema I have is that user of this class may forget to initialize some of the fields which may lead to weird behaviour. Solution that may make a sense would be to convert fields into properties and for each private field have an extra boolean that would hold the information whether the field was initialized. I can also create a megaconstructor, that would have all the fields as arguments.

在这种情况下,您会选择哪种方法?

What approach would you choose in this case?

谢谢

推荐答案

我将使用另一种方法.

  • 将另一个称为Check的方法(也许是内部方法)添加到您的CalculatorConfig类.
  • 在Calculate方法的执行过程中调用此方法.
  • 在Check方法中,验证每个参数并抛出自定义 异常是有问题的

  • Add another method (perhaps an internal method) called Check to your CalculatorConfig class.
  • Call this method inside the execution of the Calculate method.
  • In the Check method verify each parameter and throw a custom exception is something is wrong

public class CalculatorConfig 
{ 
  public double param1; 
  public double param2; 
  ... 
  internal void Check()
  {
       if(param1 == 0.0)
           throw new ArgumentException("Configuration error: param1 is not valid!");
       if(param2 == 0.0)
           throw new ArgumentException("Configuration error: param2 is not valid!");
       .... // other internal checks
  }
} 


public class Calculator 
{ 
    private CalculatorConfig _config; 
    public Calculator(CalculatorConfig config) 
    { 
        _config = config; 
    } 

    public Result Calculate(object obj)
    {
        // Throw ArgumentException if the configuration is not valid
        // Will be responsability of our caller to catch the exception
        _config.Check();

        // Do your calcs
        .....
    } 
} 

这篇关于如何确保所有类字段在首次使用之前都已初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆