Daizc
count.articles51
count.tags25
count.categories3
[Csharp]Class与RecordStruct

[Csharp]Class与RecordStruct

示例代码

为了测试在C#中ClassStructRecord三者的区别,建立了以下测试类。每个类中,分别建立了一个字段,一个自动属性,一个仅init的自动属性和一个具有私有setter的自动属性,
其中Record额外建立了一个记录属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class ClassA {
public string field;
public string Prop { get; set; }
public string PropInit { get; init; }
public string PropPrivateSet { get; private set; }
public override string ToString() {
return $"{nameof(this.field)}: {this.field}, {nameof(this.Prop)}: {this.Prop}, {nameof(this.PropInit)}: {this.PropInit}, {nameof(this.PropPrivateSet)}: {this.PropPrivateSet}";
}
}

public struct StructA {
public string field;
public string Prop { get; set; }
public string PropInit { get; init; }
public string PropPrivateSet { get; private set; }
public override string ToString() {
return $"{nameof(this.field)}: {this.field}, {nameof(this.Prop)}: {this.Prop}, {nameof(this.PropInit)}: {this.PropInit}, {nameof(this.PropPrivateSet)}: {this.PropPrivateSet}";
}
}

public record RecordA(string PropRc) {
public string field;
public string Prop { get; set; }
public string PropInit { get; init; }
public string PropPrivateSet { get; private set; }
}

反序列化测试

设计一个反序列化的测试类,对三种类型分别进行反序列化测试,三种类型均可以正常进行反序列化。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;

string str = """
{
"field":"Field",
"prop":"Prop",
"propInit":"Init Prop",
"propPrivateSet":"Private Setter Prop",
"PropRc":"Enum Main Constructor Param"
}
""";

var deserializeObject = JsonConvert.DeserializeObject<JObject>(str);
var classA = deserializeObject.ToObject<ClassA>();
var structA = deserializeObject.ToObject<StructA>();
var recordA = deserializeObject.ToObject<RecordA>();

var classB = JsonConvert.DeserializeObject<ClassA>(str);
var structB= JsonConvert.DeserializeObject<StructA>(str);
var recordB= JsonConvert.DeserializeObject<RecordA>(str);

Console.WriteLine(classA);
Console.WriteLine(structA);
Console.WriteLine(recordA);
Console.WriteLine(classB);
Console.WriteLine(structB);
Console.WriteLine(recordB);

均可以正常序列化

struct是值类型,是不可变的

copyright.author:Daizc
copyright.permalink:https://note.bequick.run/[Csharp]Class%E4%B8%8ERecord%E4%B8%8EStruct/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可