Skip to content

Introduction

jyuch edited this page Sep 2, 2015 · 10 revisions

Install

プロジェクトごとソリューションに加えるか、ダウンロードもしくはビルドしたDLLをプロジェクトの参照設定に加えてください。

現時点ではNuGetに対応してませんが、将来的にはNuGetに対応させるつもりです。

Usagi

文字列形式に表すクラスとして、今回は以下のクラスを想定します。

class Hoge
{
    public int MyProperty { get; set; }
    public string MyProperty2 { get; set; }
}

Simple ToString

そのインスタンスの文字列形式を得るだけならば、以下のコードで十分です。

static void Main(string[] args)
{
    Hoge hoge = new Hoge() { MyProperty = 1, MyProperty2 = "Hoge" };
    string str = ToStringBuilder.ToString(hoge);
    Console.WriteLine(str);
}
Hoge{MyProperty=1,MyProperty2=Hoge}

Ignoring property

Ignore null or whitespace

nullもしくはToStringの結果が空白のプロパティを無視する場合は、ToStringConfig<T>.IgnoreModeNullもしくはNullOrWhiteSpaceを指定します。

static void Main(string[] args)
{
    Hoge hoge = new Hoge() { MyProperty = 1, MyProperty2 = null };

    ToStringConfig<Hoge> conf = new ToStringConfig<Hoge>()
    {
        IgnoreMode = IgnorePropertyMode.Null
    };

    string str = ToStringBuilder.ToString(hoge, conf);
    Console.WriteLine(str);
}
Hoge{MyProperty=1}

Ignore specific property

特定のプロパティを常に無視したい場合は、ToStringConfig<T>.SetIgnorePropertyメソッドで無視するプロパティを指定します。

static void Main(string[] args)
{
    Hoge hoge = new Hoge() { MyProperty = 1, MyProperty2 = "Hoge" };

    ToStringConfig<Hoge> conf = new ToStringConfig<Hoge>();
    conf.SetIgnoreProperty(it => it.MyProperty);

    string str = ToStringBuilder.ToString(hoge, conf);
    Console.WriteLine(str);
}

Clone this wiki locally