foreach字典检查派生类

Vin*_*nay 0 c# foreach dictionary gettype getter-setter

我有一个基类 Rules.cs.有2个派生类RowRules.csColumnRules.cs.我有另一堂课Test.cs.这个类有一个Dictionary <int, Rules>不断添加值的类.当我遍历字典时,我需要知道值是RowRule还是ColumnRule.为了更好地理解,我有以下代码.

Rules.cs

class Rules
{
    private int m_timepointId = 0;
    private int m_studyId = 0;

    public int TimepointId
    {
        get { return m_timepointId; }
        set { m_timepointId = value;}
    }

    public int StudyId
    {    
        get { return m_studyId; }
        set {m_studyId = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

RowRules.cs

class RowRules : Rules
{
   private int m_row;

   public int Row
   {
       get { return m_row; }
       set { m_row = value; }
   }
}
Run Code Online (Sandbox Code Playgroud)

ColumnRules.cs

class ColumnRules: Rules
{
    private int m_column;

    public int Column
    {
        get { return m_column; }
        set { m_column = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

main class我有

private Dictionary<int, Rules> m_testDictionary = new Dictionary<int, Rules>();
ColumnRules columnrules = new ColumnRules();
RowRules rowRules = new RowRules();

rowRules.Row = 1;
rowRules.StudyId = 1;
m_testDictionary.Add(1, rowRules);

columnRules.Column = 2;
columnRules.TimepointId = 2;
m_testDictionary.Add(2, columnRules);
foreach(.... in m_testDictionary)
{
     //Need code here.
    //if(... ==  RowRules)
      {

      }
}
Run Code Online (Sandbox Code Playgroud)

现在,我需要知道foreach循环中会有什么价值.另外,我需要知道特定的字典行是a RowRule还是a ColumnRule.希望我对这个问题很清楚.任何帮助将非常感激.

dle*_*lev 5

有很多答案告诉你使用"是"来测试类型.这很好,但在我看来,如果你关掉一个物体的类型,你可能做错了什么.

通常,当您需要基类的其他各种功能时,将使用派生类.此外,ad-hoc多态通过virtualabstract方法意味着您可以让运行时计算出类型,从而导致代码更加清晰.

例如,在您的情况下,您可能希望使用方法创建Rules一个abstractabstract ApplyRule().然后,每个子类都可以实现该方法,并充分了解该类型规则的含义:

public class Rules
{
    private int m_timepointId = 0;
    private int m_studyId = 0;

    public int TimepointId
    {
        get { return m_timepointId; }
        set { m_timepointId = value;}
    }

    public int StudyId
    {    
        get { return m_studyId; }
        set {m_studyId = value; }
    }

    // New method
    public abstract void ApplyRule();
}

class RowRules : Rules
{
   private int m_row;

   public int Row
   {
       get { return m_row; }
       set { m_row = value; }
   }

   public override void ApplyRule() { // Row specific implementation }
}

class ColumnRules : Rules
{
    private int m_column;

    public int Column
    {
        get { return m_column; }
        set { m_column = value; }
    }

   public override void ApplyRule() { // Column specific implementation }
}
Run Code Online (Sandbox Code Playgroud)

现在,你的循环只是:

foreach(var kvp in m_testDictionary)
{
    kvp.Value.ApplyRule();
}
Run Code Online (Sandbox Code Playgroud)