具有不同变量的相同命名结构(类)

时间:2012-02-02 14:25:29

标签: .net class struct

我有不同的图形类,如直方图类,马类.. 他们有共同的变量但不同的属性变量。例如,所有类都有一个id,但每个类都有不同的属性变量。例如,column_width特定于直方图。现在我想使用公共类保存所有对象(每个类的实例)。我的意思是,我想编写一个带有公共变量和属性结构的类。有可能写出来吗?属性struct可以为不同的类保存不同的变量吗?我希望我能解释一下情况。

1 个答案:

答案 0 :(得分:0)

问题有点模糊,所以这只是一个草图答案。如果您需要其他答案,您可能需要更具体。无论如何,你可以从另一个类继承一个类。基类是继承的类,派生类是继承的类。派生类可以访问基类的所有公共成员和受保护成员(但不能访问私有成员)。这是一个很小的例子(甚至没有编译,但你得到了图片):

class IdentifiableBase
{
  public string id;
}

class Histogram : IdentifiableBase
{
  protected int column_width;
}

class Ma : IdentifiableBase
{
  protected string some_property_of_ma;
}

class Example
{
  public static void Main(string[] args)
  {
    IdentifiableBase[] example = new IdentifiableBase[] { new Histogram(), new Ma() };
    Console.WriteLine("{0}, {1}", example[0].id, example[1].id);
  }
}
相关问题