gpt4 book ai didi

c# - 复制构造函数转到基础构造函数并覆盖复制的值

转载 作者:太空宇宙 更新时间:2023-11-03 16:39:04 27 4
gpt4 key购买 nike

构造函数难题,我有这两个构造函数。一个用于制作类的副本,另一个用于标准构造函数。我需要调用第一个,以便我可以使用其中的规则。我不必重复代码,所以我正在寻找一种方法来避免覆盖二维。

public SprinklerLineModel()
{

NearCrossMainDimension = new PipeDimensionModel();
FarCrossMainDimension = new PipeDimensionModel();

this.AddValidationRule(Rule.CreateRule(() => BranchLineDiameter, RuleMessage.GREATER_THAN_ZERO, () => BranchLineDiameter > 0));
}

/// <summary>
/// Copy Constructor
/// </summary>
/// <param name="sprinklerLineModel">Original copy of sprinklerLineModel</param>
public SprinklerLineModel(SprinklerLineModel sprinklerLineModel)
:this()
{
this.EstimatedFlow = sprinklerLineModel.EstimatedFlow;
this.EstimatedPressure = sprinklerLineModel.EstimatedPressure;
this.NearCrossMainDimension = new PipeDimensionModel(sprinklerLineModel.NearCrossMainDimension);
this.FarCrossMainDimension = new PipeDimensionModel(sprinklerLineModel.FarCrossMainDimension);
this.BranchLineDiameter = sprinklerLineModel.BranchLineDiameter;
this.LeadLinePipeFittingLength = sprinklerLineModel.LeadLinePipeFittingLength;
this.ExbPipeFittingLength = sprinklerLineModel.ExbPipeFittingLength;

this.IsDirty = sprinklerLineModel.IsDirty;
}

我希望能够在不覆盖这两个变量的情况下调用默认构造函数。任何帮助,将不胜感激。

我想我可以检查它们是否为空,但这似乎不是最好的方法。

谢谢

最佳答案

我会提取一个初始化方法并从两个构造函数中调用该方法。

public SprinklerLineModel()
{
NearCrossMainDimension = new PipeDimensionModel();
FarCrossMainDimension = new PipeDimensionModel();
Init();
}

public SprinklerLineModel(SprinklerLineModel sprinklerLineModel)
{
this.EstimatedFlow = sprinklerLineModel.EstimatedFlow;
this.EstimatedPressure = sprinklerLineModel.EstimatedPressure;
this.NearCrossMainDimension = new PipeDimensionModel(sprinklerLineModel.NearCrossMainDimension);
this.FarCrossMainDimension = new PipeDimensionModel(sprinklerLineModel.FarCrossMainDimension);
this.BranchLineDiameter = sprinklerLineModel.BranchLineDiameter;
this.LeadLinePipeFittingLength = sprinklerLineModel.LeadLinePipeFittingLength;
this.ExbPipeFittingLength = sprinklerLineModel.ExbPipeFittingLength;
this.IsDirty = sprinklerLineModel.IsDirty;
Init();
}

void Init()
{
this.AddValidationRule(Rule.CreateRule(() => BranchLineDiameter, RuleMessage.GREATER_THAN_ZERO, () => BranchLineDiameter > 0));
}

关于c# - 复制构造函数转到基础构造函数并覆盖复制的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8199005/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com