简体   繁体   English

从基础 class 继承的字典不能从派生的 class 添加到

[英]Dictionary inherited from base class cannot be added to from derived class

I have an abstract class for POs.我有一个抽象的 class 用于采购订单。

public abstract class PO 
{
  public abstract Dictionary<string, object> InvalidFields { get; }
  public abstract string PONumber { get; set; }
}

Which is inherited by two different types of PO: CPO and POR.这由两种不同类型的 PO 继承:CPO 和 POR。

public class CPO 
{
  private string poNumber;

  public override Dictionary<string, object> InvalidFields => new Dictionary<string, object>();
  public override string PONumber
  {
    get 
    {
      return poNumber;
    }
    set 
    {
      if (!ValidatePONumber(value)) InvalidFields.Add("CPO Number", value);
      poNumber = value;
    }
  }
}

When ValidatePONumber(value) returns false , it correctly executes InvalidFields.Add() but the dictionary is never actually added to.ValidatePONumber(value)返回false时,它会正确执行InvalidFields.Add()但字典从未实际添加到。 In the Locals window, a new variable is created named Namespace.PO.InvalidFields.get returned and I can see the new key that is added.在 Locals window 中,创建了一个名为Namespace.PO.InvalidFields.get returned的新变量,我可以看到添加的新键。 However, this.InvalidFields has no values.但是, this.InvalidFields没有值。

So it looks like the dict in the abstract base class PO is being created and added to instead of the derived class CPO .所以看起来抽象基础 class PO中的 dict 正在创建并添加到而不是派生的 class CPO

The code as you have given above does not even compile.您上面给出的代码甚至无法编译。 You derived class is not actually inheriting from the abstract class (I am assuming it is a typo).您派生的 class 实际上并没有从抽象 class 继承(我假设它是一个错字)。 Even after addition abstract class, the dictionary instantiation throws an error because it is a property definition and missing 'set' definition (InvalidFields is missing 'set' accessor definition.即使在添加抽象 class 之后,字典实例化也会引发错误,因为它是属性定义并且缺少“set”定义(InvalidFields 缺少“set”访问器定义。

Also, this sounds to be a duplicate of Overriding fields or properties in subclasses此外,这听起来是覆盖子类中的字段或属性的副本

I have tried this with minor modifications, please see the code below.我已经尝试过稍作修改,请参阅下面的代码。 Like @yransis says in comments, The InvalidFields is being treated as a 'get' property, returning new instance of dictionary every time it is executing the 'Add' step.就像@yransis 在评论中所说,InvalidFields 被视为“获取”属性,每次执行“添加”步骤时都会返回字典的新实例。

class DerivedCpo : AbstractPo
{
    private string poNumber;
    private Dictionary<string, object> invalidFieldsBackingField;
    public override Dictionary<string, object> InvalidFields
    {
        get
        {
            return invalidFieldsBackingField;
        }
        set { this.invalidFieldsBackingField = value; }
    }

    public DerivedCpo()
    {
        this.InvalidFields = new Dictionary<string, object>();
    }
    public override string PoNumber
    {
        get { return poNumber;}
        set
        {
            if(!ValidatePONumber((value)))
                InvalidFields.Add("CPO Number", value);
            poNumber = value;
        }
    }



    private bool ValidatePONumber(string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            return false;
        }

        if (value.Length > 5)
            return false;

        return true;
    }
}

Main method calling this class -调用此 class 的主要方法 -

static void Main(string[] args)
{
    var po = new DerivedCpo();
    po.PoNumber = "test1";
    po.PoNumber = "thisistheinvalidfieldpo";

    if (po.InvalidFields != null && po.InvalidFields.Count > 0)
    {
        Console.WriteLine(@"There are {0} fields in invalidFields collection", Convert.ToString(po.InvalidFields.Count) );
    }

    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

In the code above I have added explicit backing field.在上面的代码中,我添加了明确的支持字段。 It is being instantiated only once in the constructor.它在构造函数中只被实例化一次。 That way the contents of InvalidFields are persistent.这样 InvalidFields 的内容是持久的。 In your code, you are returning a new instance of dictionary, essentially losing the data that was stored between two 'get' calls.在您的代码中,您将返回一个新的字典实例,实际上丢失了存储在两个“get”调用之间的数据。

Thanks to Klaus for pointing out the issue.感谢克劳斯指出问题。 I resolved by setting up a private invalidFields field and returning that with InvalidFields.get because what I was doing was returning a new Dictionary class with every get .我通过设置一个私有的invalidFields字段并使用InvalidFields.get返回它来解决,因为我所做的是在每次get时返回一个新的 Dictionary class 。

public class CPO : PO
{
  private string poNumber;
  private Dictionary<string, object> invalidFields = new Dictionary<string, object>();

  public override Dictionary<string, object> InvalidFields { get => invalidFields; }
  public override PONumber
  {
    get 
    {
      return poNumber;
    }
    set 
    {
      if (!ValidatePONumber(value)) InvalidFields.Add("CPO Number", value);
      poNumber = value;
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM