2

执行以下代码:

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

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

4

2 回答 2

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.
    }
}
于 2013-07-10T10:42:26.927 回答
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。

于 2013-07-10T10:39:27.693 回答