2010-03-03 77 views
3

我是一個試圖進入C#的Java開發人員,我試圖找到一些與Java代碼相當的代碼。在Java中,我可以這樣做:可以省略C#中抽象類中的接口方法嗎?

public interface MyInterface 
{ 
    public void theMethod(); 
} 

public abstract class MyAbstractClass implements MyInterface 
{ 
    /* No interface implementation, because it's abstract */ 
} 

public class MyClass extends MyAbstractClass 
{ 
    public void theMethod() 
    { 
     /* Implement missing interface methods in this class. */ 
    } 
} 

什麼是C#等同於此?使用abstract/new/override等最好的解決方案似乎都會導致'theMethod'被抽象類中的某種形式的主體聲明。我怎樣才能在不屬於的抽象類中去除對此方法的引用,同時在具體類中執行它呢?

回答

5

你不能,你會做這樣的:

public interface MyInterface 
{ 
    void theMethod(); 
} 

public abstract class MyAbstractClass : MyInterface 
{ 
    public abstract void theMethod(); 
} 

public class MyClass : MyAbstractClass 
{ 
    public override void theMethod() 
    { 
     /* Implement missing interface methods in this class. */ 
    } 
} 
+0

完美的,沒有方法體:)謝謝。 – izb 2010-03-03 15:46:13

2

不,你將不得不在抽象類中仍然有方法簽名,但是在派生類中實現它。

例如

public interface MyInterface 
{ 
    void theMethod(); 
} 

public abstract class MyAbstractClass: MyInterface 
{ 
    public abstract void theMethod(); 
} 

public class MyClass: MyAbstractClass 
{ 
    public override void theMethod() 
    { 
      /* implementation */ 
    } 
}