2014-10-03 2 views
4

하는의 내가 두 개의 클래스가 있다고 가정 해 봅시다 : 이제클래스 인스턴스에서 공통 함수를 호출하는 방법은 무엇입니까?

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

나는 크로스 오버가 반환하는 클래스의 인스턴스를 모르겠어요, 그것은 배트맨이 될 수 또는 수퍼맨.

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

을하지만, 수동에서는 if..else와 각 유형을 확인하지 않고 점프 기능을 실행할 수있는 방법이 .. 때 해당 변수에 저장된 클래스의 인스턴스에는 항상 점프 함수가 포함됩니다. 이 단지에 대해 경우,

public ISuperHero Crossover() 
+0

로'object',이 코드'var에 someVariableName = 크로스 오버(); someVariableName.Jump();'는 컴파일되지 않습니다. 'interface IJumpingEntity {void Jump()}'를 만들고,이 인터페이스를 구현하는'Batman'과'Superman'을 만들고'Crossover'에서 인터페이스 타입의 객체를 반환하는 것이 더 좋습니다 –

+0

Batman과 Superman이 상속받은 기본 클래스 에서 그 클래스에 점프 메소드를 넣은 다음 크로스 오버가 기본 클래스 유형의 객체를 리턴 했습니까? –

+7

친애하는 15K + 답 답장을 해주세요,이 질문이 고유하다고 확신하십니까? 몇 초 동안 답을하는 대신 참고할 질문을 찾지 않아야합니까? – CodeCaster

답변

3

여기가 인터페이스가 유용 해지는 곳입니다.

public interface ISuperhero 
{ 
    void Jump(); 
} 

그리고이 구현 :이 인터페이스 고려 그들은 개별 구현에있어

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

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

을하지만, 그들은 일반적인 다형성 인터페이스를 공유 할 수 있습니다. 귀하의 기능은 그 인터페이스를 반환 할 수 있습니다 그 인터페이스는 Jump() 방법을 가지고 있기 때문에

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

    return superman; 
} 

을, 그것을 직접 호출 할 수 있습니다 :`반환 Crossover`

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

인터페이스를 사용하여 메소드 정의). 그런 다음 파생 클래스에서 구현을 재정의 할 수 있습니다.

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(){...} 
} 
3

당신은 방법을 정의하는 기본 클래스 (또는 인터페이스를 만들 수 있습니다

interface ISuperHero 
{ 
    void Jump(); 
} 

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

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

그런 다음 당신의 방법에서 인터페이스를 반환 :

관련 문제