簡體   English   中英

將 char 轉換為 char[] 的更明智的方法是什么?

[英]What's a saner way of converting a char to a char[]?

我有類似於下面的代碼的東西。 InheritedThingchar[]? 基礎 class 中的屬性。

✅這有效:

            string mystring = "hello";
            char[] ca = { mystring[0] };
            InheritedThing = ca;

❌此快捷方式不會:

            string mystring = "hello";
            InheritedThing = { mystring[0] };

它給了我花括號下的紅色波浪線。 為什么?

是不是因為 IDE 無法確定我傳遞的是哪種數組? 如果是這樣,我如何對匿名數組進行類型轉換,以便它知道它是一個 char[]?

您可以通過在括號前添加new []來保留括號語法:

char[] InheritedThing;
var mystring = "hello";
InheritedThing = new[] { mystring[0] };

以下是使新 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' };

這最終以decimal[]結束,因為 int 和 char 可以隱式轉換為它(char 成為其 position 在字符表中的數字索引,因此 'a' 是 97)

解決一個更明智的方法:您可以使用string.ToCharArray方法,該方法采用起始索引和所需長度:

InheritedThing = mystring.ToCharArray(0, 1);

在線嘗試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM