제네릭 형식의 확장 메서드
7515 단어 extensionsdartgenerics
업데이트하려는 라이브러리의 코드에 대해 pull 요청을 생성할 필요가 없으며 새로운 기능을 코드에 로컬로 유지할 수 있습니다. 예를 들어,
Duration
형식을 지정하여 일, 시간, 분, 초를 dd:HH:MM:SS
형식으로 표시해야 하는 경우 Duration
에서 확장 메서드를 정의할 수 있습니다.extension DurationFormatter on Duration {
/// Returns a day, hour, minute, second string representation of this `Duration`.
///
///
/// Returns a string with days, hours, minutes, and seconds in the
/// following format: `dd:HH:MM:SS`. For example,
///
/// var d = new Duration(days:19, hours:22, minutes:33);
/// d.dayHourMinuteSecondFormatted(); // "19:22:33:00"
String dayHourMinuteSecondFormatted() {
this.toString();
return [
this.inDays,
this.inHours.remainder(24),
this.inMinutes.remainder(60),
this.inSeconds.remainder(60)
].map((seg) {
return seg.toString().padLeft(2, '0');
}).join(':');
}
}
void main() {
var d = Duration(days:19, hours:22, minutes:33);
print(d.dayHourMinuteSecondFormatted()); // 19:22:33:00
}
제네릭 유형에 대한 확장
Duration
와 같은 "콘크리트"유형을 확장할 수 있을 뿐만 아니라 또한 제네릭 형식의 기능을 확장하여 모든 구체적인 인스턴스(및 모든 하위 클래스)가 새 확장 메서드를 얻도록 할 수 있습니다.예를 들어
firstWhereOrNull
를 List
에 추가하려는 경우 목록에서 조건을 충족하는 첫 번째 요소를 반환하거나 해당 조건을 충족하는 요소가 없으면 null
다음과 같은 확장 메서드를 만들 수 있습니다. :extension FirstWhereOrNull<E> on Iterable<E> {
/// Returns the first element that satisfies the given predicate test.
///
/// Iterates through elements and returns the first to satisfy test.
/// If none is found, returns `null`.
E? firstWhereOrNull(bool test(E element)) {
for (E element in this) {
if (test(element)) return element;
}
return null;
}
}
void main() {
final List<String> myList = ["First", "Second", "Third"];
print(myList.firstWhereOrNull((element) =>
element.endsWith('d'))); // Second
print(myList.firstWhereOrNull((element) =>
element.startsWith('d'))); // null
}
제네릭
Iterable<E>
에 확장 메서드를 생성하여 Queue , List 및 Set 과 같은 Iterable
모든 하위 클래스의 모든 구체적인 유형에 추가하고 List<E>
에도 추가합니다.
Reference
이 문제에 관하여(제네릭 형식의 확장 메서드), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/mvolpato/extension-methods-for-generic-types-814텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)