1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#でクロージャを使いたかっただけ

1
Posted at

複数の入力があって、数値の時と文字の時で処理するクラスを選択したくて、
入力が多くなると無駄なので処理するクラスのnewは一回だけにしたくて、
入力が全部数字だったりするときに文字の方をnewしたくない
そしてインスタンス管理のためのクラスを作りたくなくて、
処理の本筋の流れにごちゃごちゃ書きたくない

という時にクロージャを使った関数で実装してみる

//本筋
public void Main(List<dynamic> args)
{
    var func = GetMethod();

    args.ForEach(input => func(input).Work(input));
}
//本筋に書きたくない部分
public Func<dynamic,IWorker> GetMethod()
{
    IWorker human = null, robot = null;

    return (input) =>
    {
        return input is int 
        ? (human ?? (human = new Human()))
        : (robot ?? (robot = new Robot()));
    };
}

使ったクラス


public interface IWorker
{
    void Work(dynamic value);
}

//数字の時に働く
public class Human : IWorker
{
    public Human() => Console.WriteLine("Human new!!");

    public void Work(dynamic value) =>  Console.WriteLine("human " + value);
}

//文字の時に動く
public class Robot : IWorker
{
    public Robot() => Console.WriteLine("Robot Created!!");

    public void Work(dynamic value) => Console.WriteLine("robot " + value);
}

入力

var values = new List<dynamic> { 1, "1", 2, "test", 3, 4, "5" };

結果

Human new!!
human 1
Robot Created!!
robot 1
human 2
robot test
human 3
human 4
robot 5
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?