C#」カテゴリーアーカイブ

プログラミング言語「C#」に関するカテゴリーです。

error CS0260: Missing partial modifier

C#のpartialを使おうとしてCS0260エラーになる場合は全てのクラスにpartialキーワードが付いているか確認してみてください。

example.cs(0,0): error CS0260: Missing partial modifier on declaration of type 'Example'; another partial declaration of this type exists

エラーになるコード

// Example.cs
public class Example : MonoBehaviour
{
  // 省略
}
// Example2.cs
public partial class Example : MonoBehaviour
{
  // 省略
}

修正したコード

// Example.cs
public partial class Example : MonoBehaviour
{
  // 省略
}
// Example2.cs
public partial class Example : MonoBehaviour
{
  // 省略
}

リンク

Compiler Error CS0260 | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0260

C#で数字を3桁ごとにコンマで区切って表示する簡単な方法

数字を3桁ごとにコンマで区切って表示したい場合、C#では文字列補間の補間式を使うと簡単にできるみたいです。

補完式の使い方は次のような感じです。

{<interpolationExpression>[,<alignment>][:<formatString>]}

サンプル

int price = 12345;
Console.WriteLine($"price: {price:#,0}");

実行結果

price: 12,345

ちなみに、string.Formatを使って実装したい場合は次のような感じになります。

サンプル

int price = 12345;
Console.WriteLine(string.Format("price: {0:#,0}", price));

実行結果

price: 12,345

リンク

$ – string interpolation – C# reference | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

C#で配列char[]をstringに変換する方法

C#でcharの配列をstringに変換する方法を調べてみたところ、次の2つが使い易そうな感じでした。

new stringを使う方法

char[] array = { 'a', 'b', 'c', 'd', 'e' };
string s = new string(array);

Console.WriteLine(s);

実行結界

abcde

string.Concatを使う方法

char[] array = { 'a', 'b', 'c', 'd', 'e' };
string s = string.Concat(array);

Console.WriteLine(s);

実行結界

abcde

他にもstring.Appendを使って1文字ずつ追加していく方法等いろいろあると思いますので、使い易い実装を探してみてください。