dart 新手,以下面的代碼為例,//void 函式不起作用,int/string 函式要么回傳列印的空值,要么回傳自動列印的值,如輸出所示。
class Microphones{
String? name;
String? color;
int? model;
String printEverything(){
print(name);
return " ";
}
int? printint(){
print(model);
}
}
void main() {
var mic1=Microphones();
print(mic1.name);
mic1.name="Yeti";
mic1.color="black";
mic1.model=26;
print(mic1.name);
print(mic1.color);
print(mic1.model);
print(mic1.printEverything());
print(mic1.printint());
}
output:
null
Yeti
black
26
Yeti
26
null
我非常感謝您在這方面的回復/幫助。
uj5u.com熱心網友回復:
null默認情況下,Dart 中的所有方法都會回傳,如果您沒有回傳任何內容(通過return在方法中指定回傳空值或在方法中void根本沒有任何return回傳void或可空型別,如int?)。
但是方法簽名中的回傳型別指定了方法的呼叫者應該如何查看值。在這里,我們void在 Dart 語言之旅中將其描述為:
一種特殊型別,表示從未使用過的值。
https://dart.dev/guides/language/language-tour#a-basic-dart-program
所以我們指定void向我們的方法的用戶發出信號,永遠不應該使用回傳的值。然后 Dart 分析器和編譯器會非常努力地確保您最終沒有使用 typed 的回傳值void。
好奇的進階部分
但這并不意味著不可能使用void由方法簽名指定的回傳值:
void someMethod() {
void someVoidVariable = 'Hey, I am a String!';
return someVoidVariable;
}
void someOtherMethod() => 'Hey, I am also a String!';
void main() {
print(someMethod() as String); // Hey, I am a String!
print(someOtherMethod() as String); // Hey, I am also a String!
}
在第一個例子中,我們強制 Dart 看到我們的Stringas void。這完全沒問題,因為所有型別都可以看作void. 然后我們被允許回傳這個void值,因為someMethod()假設回傳void。
這種強制的原因是 Dart 會抱怨(這是有道理的,因為我們所做的非常愚蠢,永遠不應該出現在真正的程式中):
void someMethod() {
return 'Hey, I am a String!';
// ERROR: A value of type 'String' can't be returned from the function
// 'someMethod' because it has a return type of 'void'.
}
或者這是因為我們不能轉換為voidusing as:
void someMethod() {
return 'Hey, I am a String!' as void; // ERROR: Expected a type name.
}
然后我們將它轉??換void回 aString以讓 Dart 允許我們使用回傳的值 in print()(因為 Dart 否則會阻止我們嘗試使用void型別化的值)。
在第二個例子中,我展示了為什么事情像現在這樣作業的原因之一。在 Dart 中,我們可以撰寫這兩個方法,它們將執行完全相同的操作(注意我將回傳型別更改String為本示例):
String someOtherMethod() {
return 'Hey, I am also a String!';
}
String someOtherMethod() => 'Hey, I am also a String!';
因此,第二種方式是我們是否只想執行單個陳述句并回傳其值的簡寫。
但是關于:
void someOtherMethod() => 'Hey, I am also a String!';
If we followed the traditional rules, this would not be allowed since we cannot return a String since we have typed void. But sometimes, we also want to use this simple syntax to just execute a method and don't want to care about what that method would end up returning.
E.g. this:
final someList = <String>[];
void removeStringFromList(String string) => someList.remove(string);
Where the remove method on List is actually returning a bool which indicate if the element was inside the list.
So Dart ignores this problem when we use the => by just casting the result to void in this case. So in our last example, the returned bool is actually returned to the caller of removeStringFromList but because its type has been cast to void, the caller of removeStringFromList is prevented (in a lot of ways) from using the value.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/329552.html
上一篇:知道是什么原因導致Android上Xamarin.Forms中的非托管代碼出現java.util.concurrentModificationException嗎?
