我有類似于下面的代碼的東西。InheritedThing是char[]?基類中的屬性。
?這有效:
string mystring = "hello";
char[] ca = { mystring[0] };
InheritedThing = ca;
?此快捷方式不會:
string mystring = "hello";
InheritedThing = { mystring[0] };
它給了我花括號下的紅色波浪線。為什么?
是不是因為 IDE 無法確定我傳遞的是哪種陣列?如果是這樣,我如何對匿名陣列進行型別轉換,以便它知道它是一個 char[]?
uj5u.com熱心網友回復:
以下是使新 char 陣列初始化為一個值的選項(不依賴于回傳 char 陣列的方法):
//when you're declaring the variable too
char[] c = new char[] { 'x' };
char[] c = new[] { 'x' };
char[] c = { 'x' };
var c = new char[] { 'x' };
var c = new[] { 'x' };
//when assigning to an existing variable, new keyword I required
Thing = new char[] { 'x' };
Thing = new[] { 'x' };
我傾向于在new[] { ... }任何地方使用快捷方式,因為無論背景關系如何,它都能始終如一地作業(除非 c# 版本太舊而無法使用)。可能還值得注意的是,在編譯器確定陣列型別的情況下,它只使用第一個元素,因此只要它們可以隱式轉換為第一個元素的型別,就可以放置不同的型別
var nums = new[] { 1m, 1, 'a' };
這以 a 結束,decimal[]因為 int 和 char 可以隱式轉換為它(char 成為其在字符表中位置的數字索引,因此 'a' 是 97)
uj5u.com熱心網友回復:
解決一種更明智的方法:您可以使用string'.ToCharArray方法,該方法采用起始索引和所需長度:
InheritedThing = mystring.ToCharArray(0, 1);
在線嘗試
uj5u.com熱心網友回復:
new []您可以通過在括號前添加右括號來保留括號語法:
char[] InheritedThing;
var mystring = "hello";
InheritedThing = new[] { mystring[0] };
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/419870.html
標籤:
上一篇:例如,如何從電話簿中的C#中將文本檔案中的單個人的詳細資訊顯示到控制臺上?
下一篇:為什么在使用Prepare()方法時會出現語法錯誤?沒有“addCustCmd.Prepare();”,問題就消失了
