2
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?

C#初心者の学習記録

2
Posted at

はじめに

今回はC#の学習記録として簡単なスクリプトを書きました。
学習記録として随時記載していきます。
特段の目的等はありませんので、ご了承ください。

実行環境

・windows:Windows11Pro 23H2

準備や実行方法

・dotnet-scriptのインストール
 dotnet tool install -g dotnet-script
・csx形式の実行ファイルを用意する
・ターミナルで実行する
 dotnet script ファイル名

スクリプト

test.csx
using System;
using System.Collections.Generic;

// 抽象データ型(ADT)
public interface IDog{
    string Name{get;set;}
    int Age{get;set;}
    void Bark();
    void Introduce();
}

public class Dog : IDog{
    public string Name{get;set;}
    public int Age{get;set;}
    public void Bark()
    {
        Console.WriteLine($"{Name} is cry -> wanwan");
    }
    public void Introduce()
    {
        Console.WriteLine($"My name is {Name},Age -> {Age}");
    }
}

public class ShibaInu : IDog{
    public string Name{get;set;}
    public int Age{get;set;}
    public void Bark()
    {
        Console.WriteLine($"{Name} barks with pride -> woo");
    }
    public void Introduce()
    {
        Console.WriteLine($"ShibaInu My name is {Name},Age -> {Age}");
    }
}

// ファクトリクラス
public interface IDogFactory{
    IDog CreateDog(string type,string name,int age);
}

public class DogFactory : IDogFactory{
    public IDog CreateDog(string type,string name,int age){
        return type.ToLower() switch{
            "shiba" => new ShibaInu {Name = name,Age = age},
            "default" => new Dog {Name = name,Age = age},
            _ => throw new ArgumentException($"Unknown dog type : {type}")
        };
    }
}

// DI対象クラス
public class DogService{
    private readonly IDog _dog;
    public DogService(IDog dog){
        _dog = dog;
    }
    public void Run(){
        _dog.Introduce();
        _dog.Bark();
    }
}

// 実行コード:DI + ファクトリ
IDogFactory factory = new DogFactory();

List<DogService> services = new List<DogService>{
    new DogService(factory.CreateDog("default","Poti",3)),
    new DogService(factory.CreateDog("shiba","Koro",5))
};

foreach (var service in services){
    service.Run();
}

実行結果

My name is Poti,Age -> 3
Poti is cry -> wanwan
ShibaInu My name is Koro,Age -> 5
Koro barks with pride -> woo
2
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
2
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?