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

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

C#でプロパティーを使ったinterfaceの使い方

C#でプロパティーを使ったinterfaceの使い方をよく忘れてしまうので、メモしておこうかなと思います。

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

インターフェース

public interface IExample
{
  string Name
  {
    get;
    set;
  }
}

使っているところ

using System;

public class Example : IExample
{
  string _name = "";

  public string Name
  {
    get { return _name; }
    set { _name = value; }
  }

  public Example(string name)
  {
    _name = name;
  }
}

public class TestExample
{
  static public void Main ()
  {
    IExample example = new Example("name");

    Console.WriteLine($"example.name = {example.Name}");

    example.Name = "new name";
    Console.WriteLine($"example.name = {example.Name}");
  }
}

実行結果

example.name = name
example.name = new name

何故かよく忘れてしまいます。

リンク

Interface Properties – C# Programming Guide | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/interface-properties

C#で文字列の分割

C#ではSplitというメソッドを使うことで簡単に文字列の分割ができます。
使い方は次のような感じです。

コンマ「,」かハイフン「-」で分割

using System;

class Example1
{
  static public void Main()
  {
    string str = "one,two-three";
    char[] sep = { ',', '-' };

    string[] ar = str.Split(sep, StringSplitOptions.None);

    foreach(string s in ar) {
      Console.WriteLine(s);
    }
  }
}

実行結果

one
two
three

連続した3つのハイフン「---」で分割

using System;

class Example2
{
  static public void Main()
  {
    string str = "one---two-three";
    string[] sep = { "---" };

    string[] ar = str.Split(sep, StringSplitOptions.None);

    foreach(string s in ar) {
      Console.WriteLine(s);
    }
  }
}

実行結果

one
two-three

他に、正規表現を使って分割したりもできます。

リンク

String.Split Method (System) | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/api/system.string.split

C#のプロパティーの簡潔な書き方

C#でプロパティーという書き方がありますが、使っていますか?

float width
{
  get { return size.width; }
}

みたいな書き方です。

これは次のような感じで省略して書くことができるみたいです。

float width => size.width;

setも使いたい場合は少し長くなりますが、次のような感じです。

float width
{
  get => size.width;
  set => set.width = value;
}

Visual Studioの表示で教えてもらったのですが、短かくて読み易くなったような気がします。

リンク

Properties – C# Programming Guide | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties