c# inheritance: change field data type and value in derived class

那年仲夏 提交于 2021-02-19 06:15:33

问题


Is it possible to change a base class field data type and value in the derived class and still call the base class method but use the derived class values?

Sample Code:

public class class1 
{
  protected DBContext DB { get; set; }

  public A() 
  {
    DB = new DBContext();
  }

  public virtual DBRecord find(int id)
  {
    return DB.DBRecord.Find(id);
  }
}

public class class2 : class2
{
  protected DifferentDBContext DB { get; set; }

  public B()
  {
    DB = new DifferentDBContext();
  }
}

And then i tried to call the method with the code below.

class2 x = new class2();
x.find(1); // calls the base class method with base class field values

Basing on what's happening, it's calling the base class method with the base class variables. I want to know if it's possible to set the field type/value in derived class and then call the base class method? because they just have the same implementation but just using different values.

What I've done so far (which i feel is so redundant) and working.

public class class2 : class1 
{
  //Other implementations omitted
  public override DBRecord find(int id)
  {
    return DB.DBRecord.Find(id);
  }
}

Note: this may be just a simple OOP principle but you know, people get confused with that sometimes, just like me :-)


回答1:


The way to do this is to make your property virtual in the base class:

public class class1 
{
  protected virtual DBContext DB { get; set; }
  ...
}

And then override it in the derived class:

public class class2 : class1
{
  private DifferentDBContext DDB;
  protected override DBContext DB 
  { 
    get { return DDB; } 
    set { DDB = value is DifferentDBContext ? (DifferentDBContext)value : null; } 
  }
}

This is assuming that DifferentDBContext is a DBContext.




回答2:


You should either use an interface of the db context or the base class of the db context.

public interface IDbContext{}
public class ContextA : IDbContext{}
public class ContextB : IDbContext{}

public class A
{
      protected IDbcontext DB { get; set; }
      public A(IDbcontext db)
      {
           DB = db;
      }
}
public class B : A
{
      public B():this(new ContextB(){}
      public B(IDbcontext db):base(db){}
}

Some like that, similar approach with inherited contexts as well.

Yet another approach can be to have an abstract base class where the base class asks for the dbcontext, either through interface or inheritance again.



来源:https://stackoverflow.com/questions/47124390/c-sharp-inheritance-change-field-data-type-and-value-in-derived-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!