简体   繁体   English

有没有办法将 object 序列化/反序列化为 C# 中的字符串?

[英]Is there a way to serialize / deserialize an object to a string in C#?

Is there any kind of text serializer in C#, which is able to serialize / deserialize this shortened example... C# 中是否有任何类型的文本序列化程序,能够序列化/反序列化这个缩短的示例...

public class Record
{
    // Letters 1-4
    public string Identifier { get; set; }

    // Letters 5-12
    public string ProcessAbbreviation { get; set; }

    // Letters 13-16
    public string Name { get; set; }
}

... into this string? ...进入这个字符串?

AAAABBBB    CCCC

Note, that the string must contain whitespaces if the property hasn't the desired length.请注意,如果属性没有所需的长度,则字符串必须包含空格。

Although it must be possible to serialize / deserialize into the other direction, eg string into object.虽然必须可以序列化/反序列化到另一个方向,例如字符串到 object。

I've already tried to find something, which suits my requirement, but I couldn't find anything.我已经尝试找到适合我要求的东西,但找不到任何东西。

I highly appreciate any kind of help, cheers: :)我非常感谢任何形式的帮助,干杯::)

There's not going to be an existing library to do this, but it's very easy to write your own serialisation and deserialisation:不会有现有的库来执行此操作,但是编写自己的序列化和反序列化非常容易:

public class Record
{
    // Letters 1-4
    public string Identifier { get; set; }

    // Letters 5-12
    public string ProcessAbbreviation { get; set; }

    // Letters 13-16
    public string Name { get; set; }

    public string Serialize()
    {
        return $"{Identifier, -4}{ProcessAbbreviation, -8}{Name, -4}";
    }

    public static Record Deserialize(string input)
    {
        if (input is not { Length: 16 })
            throw new ArgumentException("input must be 16 characters long");

        return new Record
        {
            Identifier          = input.Substring( 0, 4).Trim(),
            ProcessAbbreviation = input.Substring( 4, 8).Trim(),
            Name                = input.Substring(12, 4).Trim()
        };
    }
}

Test code:测试代码:

public static void Main()
{
    var rec = new Record { Identifier = "AAAA", ProcessAbbreviation = "BBBB", Name = "CCCC" };

    var serialised = rec.Serialize();
    Console.WriteLine("|" + serialised + "|");

    var r = Record.Deserialize(serialised);

    Console.WriteLine($"|{r.Identifier}|{r.ProcessAbbreviation}|{r.Name}|");
}

Try it on DotNetFiddle在 DotNetFiddle 上试试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM