如何在类实例中调用常用函数?

时间:2014-10-03 13:19:37

标签: c#

假设我有两个班级:

class Batman
{
    public void Robin(){...}
    public void Jump(){...}
}

class Superman
{
    public void Kryptonie(){...}
    public void Jump(){...}
}

现在,我有一个这样的类的实例:

public object Crossover()
{
     var batman = new Batman();
     var superman = new Superman();

     return superman;
}

我不知道Crossover将返回哪个类的实例,它可能是蝙蝠侠或超人。

var someVariableName = Crossover(); //I don't know if this contains an instance of Superman or Batman;

//I do know that no matter which class instance is returned, it will always contain a function named Jump which i want to trigger:
someVariableName.Jump();

现在我知道我可以做类似的事情:

if (someVariableName.GetType() == typeof(Superman)) 
{
    ((Superman) someVariableName).Jump()
}

但是有没有办法触发Jump函数而不必用if..else手动检查每个类型..当我知道保存在该变量中的类的实例将始终包含Jump函数时? / p>

3 个答案:

答案 0 :(得分:14)

使用界面:

interface ISuperHero
{
    void Jump();
}

class Batman : ISuperHero
{
    public void Robin(){...}
    public void Jump(){...}
}

class Superman : ISuperHero
{
    public void Kryptonie(){...}
    public void Jump(){...}
}

然后从您的方法返回界面:

public ISuperHero Crossover()

答案 1 :(得分:3)

您可以创建一个定义方法的基类(或接口,如果只是方法定义)。您可以在派生类中覆盖实现。

abstract class ActionFigure
{
    public abstract void Jump(); // just define it has a Jump method, but implement it in the deriving class

    public void SomethingGeneral()
    {
        // no need for an override, just implement it here
    }
}

class Batman : ActionFigure
{
    public void Robin(){...}
    public override void Jump(){...}
}

class Superman : ActionFigure
{
    public void Kryptonie(){...}
    public override void Jump(){...}
}

答案 2 :(得分:3)

这是接口变得有用的地方。考虑一下这个界面:

public interface ISuperhero
{
    void Jump();
}

这些实施:

class Batman : ISuperhero
{
    public void Robin(){...}
    public void Jump(){...}
}

class Superman : ISuperhero
{
    public void Kryptonie(){...}
    public void Jump(){...}
}

它们是单独的实现,但它们共享一个共同的多态接口。然后,您的函数可以返回该接口:

public ISuperhero Crossover()
{
     var batman = new Batman();
     var superman = new Superman();

     return superman;
}

由于该接口具有Jump()方法,因此可以直接调用它:

var someVariableName = Crossover();
someVariableName.Jump();