c#继承:在派生类中更改字段数据类型和值 [英] c# inheritance: change field data type and value in derived class

查看:49
本文介绍了c#继承:在派生类中更改字段数据类型和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在派生类中更改基类字段数据类型和值,并且仍然调用基类方法但使用派生类值?

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?

示例代码:

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);
  }
}

注意:这可能只是一个简单的 OOP 原则,但您知道,人们有时会对此感到困惑,就像我一样 :-)

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

推荐答案

这样做的方法是在基类中让你的属性成为虚拟的:

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; } 
  }
}

这里假设 DifferentDBContext 是一个 DBContext.

This is assuming that DifferentDBContext is a DBContext.

这篇关于c#继承:在派生类中更改字段数据类型和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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