我可以有一个基类,每个派生类都有自己的静态属性副本吗? [英] Can I have a base class where each derived class has its own copy of a static property?

查看:125
本文介绍了我可以有一个基类,每个派生类都有自己的静态属性副本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似下面的情况:

class Base
{
     public static int x;
     public int myMethod()
     {
          x += 5;
          return x;
     }

}

class DerivedA : Base
{
}

class DerivedB : Base
{
}

我试图设置它以便每个派生类都有它自己的静态x实例,如果我做这样的事情:

I am trying to set this up so that each derived class has its own static instance of x, if I do something like this:

 DerivedA.x = 5;
 DerivedB.x = 10;

然后当我跑:

 DerivedA.myMethod(); //The result will be 10
 DerivedB.myMethod(); //The reusult will be 15

我可以这样做吗?如何设置派生类来实现此目的?谢谢你们。

Can i do something like this? How can I setup the derived classes to achieve this? Thanks guys.

编辑:基本上,我有一堆派生类,每个派生类都有一个独特的属性。它不会因每个实例而异,因此我认为应该是一个静态变量。此外,该属性由方法设置,对于每个类都是相同的。
我试图避免在每个派生类中复制和粘贴该属性和方法的逻辑。我认为最好以某种方式将该逻辑移动到从中派生每个类的基类。但是,我需要每个派生类都有自己的属性副本。
我不一定非必须这样做,如果你们有任何建议,我会很高兴听到一些更好的做法建议..谢谢!

Basically, I have a bunch of derived classes that each have a property unique to that class. It does not vary for each instance, and thus I believe should be a static variable. Also, that property is set by a method, that is the same for each of these classes. I am trying to avoid having to copy and paste the logic for that property and method in each of these derived classes. I thought it best to somehow move that logic to the base class from which each of these classes are derived from. But, I need each derived class to have its own copy of that property. I do not necessarily have to do it this way, and I will be happy to hear some better practices suggestions if you guys have any.. Thanks!

推荐答案

您需要在所有派生类型中重新定义和隐藏字段和方法。

You will need to redefine and hide the field and method in all derived types.

示例:

class DerivedA : Base
{
  public new static int x;
  public new int myMethod()
  {
    x += 5;
    return x;
  }
}

注意:不要这样做。修复你的设计。

Note: don't do it this way. Fix your design.

编辑:

实际上,我有一个类似的结构。我用一个抽象(如果你需要一个默认值,使用 virtual )属性解决它,然后从基类中使用它:

Actually, I have a similar construct. I solve it with an abstract (if you need a default value, use virtual) property which then gets used from the base class:

public abstract class Base
{
   public abstract string Name { get; }

   public void Refresh()
   {
     //do something with Name
   }
}

public class DerivedA
{
  public override string Name { get { return "Overview"; } }
}

您应该能够针对您的用例进行调整。如果只有派生类应该能够看到它,你当然可以使属性受保护

You should be able to adjust that for your use case. You can of course make the property protected if only deriving classes should be able to see it.

这篇关于我可以有一个基类,每个派生类都有自己的静态属性副本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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