向下转向哪个对象

时间:2013-07-10 10:33:21

标签: c# .net

执行以下代码:

ClassA myClass = new ClassA()
myClass.varA = "Teststring"

BaseClassB cls = new BaseClassB()
cls.methodA(myClass)

我有以下课程

class BaseClassA
{

}

class ClassA:BaseClass
{
   string varA;
}

class ClassB:BaseClass
{
   string varB;
}

然后是一种方法

class BaseClassB
{
   public void methodA(BaseClassA myVar)
   {
      // How can I display varA that is given with myClass (which is myVar)?
      // It should also be able to display varB when an object of type ClassB is given
      // So I have to make a downcast here but I don't know if I have to downcast to ClassA or ClassB
   }
}

我知道这是主要知识,但有人可以帮助我吗?

2 个答案:

答案 0 :(得分:7)

您可能希望重新构建代码,而不是将代码放在您指定的位置。基类的重点在于您可以将ClassA和ClassB视为相同。如果你想以不同方式对待它们,那么就要有带ClassA和ClassB对象的重载......

class BaseClassB
{
    public void methodA(ClassB myVar)
    {
        Console.WriteLine(myVar.varB);
        methodCommon(myVar);
    }
    public void methodA(ClassA myVar)
    {
        Console.WriteLine(myVar.varA);
        methodCommon(myVar);
    }
    public void methodCommon(BaseClassA myVar)
    {
    }
}

如果您真的需要一种方法,那么您可以这样做:

public void methodA(BaseClassA myVar)
{
    if (myVar is ClassA)
    {
        //Its of type ClassA so you can do whatever you want with it knowing it is a ClassA.
    }
    else if (myVar is ClassB)
    {
        //Its of type ClassB so you can do whatever you want with it knowing it is a ClassB.
    }
    else
    {
        //Its not either.
    }
}

答案 1 :(得分:2)

如果你确定myVar是ClassA或ClassB,你可以这样做:

string s;
var myvarA = myVar as ClassA;
if (myvarA != null)
{
    s = mayVarA.varA;
}
else
{
    s = ((myvarB)myVar).varB;
}

如果myVar可以是其他东西,那么你可以做同样的测试而不是ClassA的ClassB。