如何將型別串列(不是實體串列!)傳遞給方法?如果一個實體匹配串列中的任何型別,你如何比較?
例如:這個偽代碼想要做一些事情,如果someInstance它的型別與typesOfInterest.
void doSomethingWithSpecificTypesOnly<T>(List<T> typesOfInterest) {
Object someInstance;
for (T thisType in typesOfInterest) {
if (someInstance is thisType) {
// do something...
}
}
}
問題是,我無法弄清楚語法,因此非常感謝您的幫助。謝謝你。
uj5u.com熱心網友回復:
我建議使用您需要的操作創建“型別”的表示。(這個Type類很可能不是這樣,因為它除了相等之外沒有其他操作。)
就像是:
class MyType<T> {
bool isInstance(Object? object) => object is T;
bool operator >=(MyType other) => other is MyType<T>;
bool operator <=(MyType other) => other >= this;
R runWith<R>(R Function<X>() function) => function<T>();
}
void doSomethingWithSpecificTypesOnly<T>(List<MyType<T>> typesOfInterest) {
Object someInstance;
for (T thisType in typesOfInterest) {
if (thisType.isInstance(someInstance)) {
// do something...
}
}
}
通過將型別保留為型別引數,它可以作為型別變數來訪問您想要執行的任何操作,并且可以在需要型別的大多數地方使用。不可能從Type物件回傳到型別變數,并且Type變數的功能非常有限。
這確實意味著您需要撰寫更多代碼來創建MyType物件:
doSomethingWithSpecificTypesOnly<num>([MyType<int>(), MyType<double()]);
您可能可以為此創建一個速記,例如:
typedef T<X> = MyType<X>;
然后改寫[T<int>(), T<double>()]。略短。或者
extension StaticType<T> on T {
MyType get staticType => MyType<T>;
}
并執行以下操作:
[1.staticType, 1.1.staticType, "".staticType]
有很多選項,具體取決于您想要的 API,但它不會那么短[int, double],它比使用Type物件更強大。
uj5u.com熱心網友回復:
這可能是您要查找的內容,但是它將與確切的型別匹配:
class SomeClass {
}
void doSomethingWithSpecificTypesOnly<T>(List<Type> typesOfInterest, T obj) {
for (Type t in typesOfInterest) {
if (obj.runtimeType == t) {
print('ok');
print(obj.runtimeType);
}
}
}
void main() {
SomeClass obj = SomeClass();
doSomethingWithSpecificTypesOnly([int, SomeClass], obj);
doSomethingWithSpecificTypesOnly([int, double], obj);
return;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/486642.html
標籤:镖
