簡體   English   中英

Dart:如何為抽象 Class 創建最終成員接口

[英]Dart: how to create a Final member Interface for Abstract Class

我想強制 Class User從抽象 class Base實現 static 成員。 這是可能的,還是我錯誤地使用了抽象的 inheritance 范式?

Without inheritance, the User can simply implement its own static member without overriding the Base , but I would like my linter to throw a warning when a Class does not implement some static member.

什么有效(不強制執行界面)

我們可以在BaseUser中隱式使用相同的接口。

abstract class Base {
  // This member could simply be removed and the snippet would still compile.
  static final String routeName = '/base';
}

class User extends Base {
  static final String routeName = '/base/user';
}

如果我們要創建一個同樣擴展Base的新 Class Person ,我們沒有具體的實現要求。 理想情況下,我想強制Person擁有一個 static 成員routeName

class Person extends Base {
  // No warning about a missing static member 'routeName'.
}

想法的例子(不編譯)

Base將包含一個未實現的 static 成員( routeName )。

除非我們指定routeName (例如routeName = '/base' ),否則此代碼段不會編譯。

abstract class Base {
  // IDE Error: The final variable 'routeName' must be initialized.
  static final String routeName;
}

實現BaseUser將覆蓋或實現 static 成員。

該片段會報告警告,除非我們刪除錯誤放置的@override

class User extends Base {
  // IDE Warning: Field doesn't override an inherited getter or setter.
  @override
  static final String routeName = '/base/user';
}

我希望 IDE 為Person Class 引發錯誤,因為它沒有實現 static 成員routeName

class Person extends Base {
  // Expected IDE Error: The static final variable 'routeName' must be initialized.
}

對我來說,這看起來類似於Java 的做法,但我不熟悉 Java 的細節。

不,這是不可能的。 Static 成員不被繼承,它們不是任何接口的一部分,也不是虛擬的,所以你不能“覆蓋”。 @override注釋根本不適用於 static 聲明。

您可以在兩個類上使用具有相同名稱的 static 吸氣劑,但它們完全不相關,並且不必具有相同的類型甚至簽名(一個可以是 function,另一個是吸氣劑,完全不相關的聲明)。 每次訪問其中一個都必須直接在源代碼中選擇哪一個。

(Java "inherits" static members only in the sense that you can call them on subclasses too, unless the subclass declares a static with the same name and signature - since Java has overloading - but you don't get any kind of virtual override or后期綁定。在編寫調用時,您仍然可以選擇使用哪個。您只是有更多方法來編寫相同的內容。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM