[toc]
代码编写技巧
1 2 3 4 5
| self.selectedBackgroundView = ({ UIView *view = [UIView new]; view.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1.0]; view; });
|
枚举转 int AvatarStatus
协变和逆变 ?= 策略
在Dart1.x的版本种是既支持协变又支持逆变,但是在Dart2.x版本开始仅支持协变。所以后面我们就不再讨论Dart的逆变。
1 2 3 4 5 6 7 8 9
| class PrintMsg<T> {
T _msg;
set msg(T msg) { this._msg = msg; }
void printMsg() { print(_msg); }
}
|
T
是一个抽象类型,因此无法直接使用T(a: "hello")
来创建实例。我们需要稍微修改一下代码,以便在test()
方法中正确创建T
的实例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| abstract class A { String? a; A({this.a}); }
class A1 extends A { A1({String? a}) : super(a: a); }
class A2 extends A { A2({String? a}) : super(a: a); }
class B<T extends A> { T createInstance() { if (T == A1) { return A1(a: "hello") as T; } else if (T == A2) { return A2(a: "world") as T; } else { throw Exception("Unsupported type"); } }
void test() { T bean = createInstance(); print(bean.runtimeType); } }
void main() { B<A1>().test(); B<A2>().test(); }
|