[英]Java can combine default implementation from an abstract class and interface in a class. Is there a way to achieve this in C#?
在使用接口和抽象 class 時,是否有一種“智能”方法可以實現與 Java 相同的結果,這兩者都實現了自己的一半共享接口?
在 Java 中,我能夠擴展一個抽象 class ( AnAbstractClass
) 並實現一個接口 ( AnotherInterface
),每個接口都有一個接口部分 ( AnInterface
) 的默認實現,這樣我就不必在其中實現任何方法結合這些的 class(見代碼)。
我正在嘗試將 Java 代碼轉換為 C#,同時確保所有內容都一對一映射。 所以我想盡可能避免創建新類,並且我的“Combiner”class 不包含任何方法。
public class Test{
public interface AnInterface
{
String methodOne();
int methodTwo();
}
public interface AnotherInterface extends AnInterface
{
default int methodTwo()
{
return 2;
}
}
public abstract class AnAbstractClass implements AnInterface
{
public String methodOne()
{
return "1";
}
}
public class Combiner extends AnAbstractClass implements AnotherInterface
{
}
}
這在 C# 中是可以實現的,但據我所知,沒有聰明的方法可以做到這一點,因為接口通常應該保持簡單,這只會讓代碼更難閱讀和調試。
public interface IAnInterface
{
public string MethodOne();
public int MethodTwo();
}
public interface IAnotherInterface : IAnInterface
{
public static new int MethodTwo()
{
return 2;
}
}
public abstract class AnAbstractClass : IAnInterface
{
public string MethodOne()
{
return "1";
}
public abstract int MethodTwo();
}
public class Combiner : AnAbstractClass, IAnotherInterface
{
public override int MethodTwo()
{
return IAnotherInterface.MethodTwo();
}
}
所以我懇求你不要這樣做!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.