【问题标题】:Is there a way to initialize properties after construction of object?有没有办法在构造对象后初始化属性?
【发布时间】:2014-12-04 10:52:39
【问题描述】:

我有一个像这样的Conversion 类:

public class Conversion
{
    public memorySource MSource { get; set; }
    public Rule[] Rules { get; set; }
    public Conversion(XElement xElement)
    {
       // I use Rules property here 
       // From Rules property and xElement parameter i initialize MSource Property
    }

    public Conversion(ExcelPackage)
    {
       // Also i use Rules property here 
       // From Rules property and xElement parameter i initialize MSource Property
    }
}

当我想构造Conversion 类的实例时,我这样做:

Conversion cvr = new Conversion(xElement) { Rules = rules };

然后我得到这个错误:

对象引用未设置为对象的实例

我知道对象的构造是在初始化属性之前开始的,但是有没有办法逆向?

我可以使用 Rules 属性作为构造函数的参数,但它不适合性能,因为我有多个构造函数。

【问题讨论】:

  • 您必须在构造函数中初始化规则,或者添加另一个接受规则的构造函数,如您所说。没有别的办法

标签: c# .net constructor object-initializers


【解决方案1】:

是的,只需在构造函数中将值作为参数传递。这是唯一的方法:

Conversion cvr = new Conversion(rules, package);

构造函数在哪里:

public Conversion(Rule[] rules, ExcelPackage package)
{
   this.Rules = rules;

   ...
}

您可以为其他构造函数默认rules 参数,因此您不必重复代码:

public Conversion(ExcelPackage package) : this(new Rule[] { ... }, package)
{
   ...
}

【讨论】:

  • 哦,我没看到你已经展示了: this 的示例,所以我删除了我的。
  • OP做的方式不行吗??
  • @EhsanSajjad:如果您打算在构造函数中使用Rules,则不会。对象初始化器是构造函数后的操作。
  • @PatrickHofman 我在 Albahari 书中学习,我记得我们可以这样写
  • @EhsanSajjad:你可以,但这会在构造函数之后初始化Rules。 OP 需要 Rules in 构造函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
相关资源
最近更新 更多