LoginSignup
1
0

More than 3 years have passed since last update.

C#のToStringについて

Last updated at Posted at 2020-07-05

記事を書いたきっかけ

intやfloat、bool、Vector3の値をシリアライズしてデシリアライズできる処理を実装しようと思って行きついたのが、このToString()。やってることの説明としてはintやfloatの値を文字列として外部に出力して、デシリアライズする際にその値の型で文字列から値に変換している。

実際のコード

下記ではVector3NodeっていうクラスでVector3の値をシリアライズ、デシリアライズしている。

Vector3Node.cs
public class Vector3Node : PropertyNode
{
    private Vector3Field vec3Field;

    public Vector3 Value { get { return vec3Field.value; } set { vec3Field.value = value; } }
    public Vector3Node() : base()
    {
        CreateOutputPort<Vector3>(Port.Capacity.Multi, "Vector3");
        vec3Field = new Vector3Field();
        mainContainer.Add(vec3Field);
    }
    public override string SerializeProperty()
    {
        return Value.ToString();
    }
    public override void DeserializeProperty(string _propertyValue)
    {
        var elements = _propertyValue.Trim('(', ')').Split(',');

        if(elements.Length <= 3)
        {
            var vec = Vector3.zero;
            vec.x = float.Parse(elements[0]);
            vec.y = float.Parse(elements[1]);
            vec.z = float.Parse(elements[2]);
            Value = vec;
        }
    }
}

シリアライズ用の関数でVector3の数値を文字列で返し、デシリアライズの際に渡された文字列を3つに分解してVector3の各メンバに代入して処理させています。
BaseNodeクラスの方でデシリアライズ用の関数を抽象メソッドとして定義して、各クラスでオーバーライドしています。
こうすることで型ごとのクラスで型を意識することなく、文字列でデータの読み書きができるようになります。

後はこのVector3用のParseの処理を拡張メソッドとしてリファクタリングすれば汎用性が出そうですね。

参考サイト

文字列から数値、数値から文字列への変換
https://dobon.net/vb/dotnet/programing/convert.html

Vector3の文字列から値へのの変換の方法
https://teratail.com/questions/109274

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