gpt4 book ai didi

c# - 在 C# 中比较两个结构的值

转载 作者:太空狗 更新时间:2023-10-29 22:25:06 25 4
gpt4 key购买 nike

我不是在寻找返回 bool 的两个结构的比较,我想知道是否有办法获取两个结构(相同的结构,但可能不同的值)的哪些字段不同。基本上我想要一种更简单的方法来执行以下操作:

public class Diff
{
public String VarName;
public object Val1;
public object Val2;

public Diff(String varName, object val1, object val2)
{
VarName = varName;
Val1 = val1;
Val2 = val2;
}

public override string ToString()
{
return VarName + " differs with values " + Val1 + " and " + Val2;
}
}

public struct TestStruct
{
public int ValueOne;
public int ValueTwo;
public int ValueThree;

public List Compare(TestStruct inTestStruct)
{
List diffs = new List();
if (ValueOne != inTestStruct.ValueOne)
{
diffs.Add(new Diff("ValueOne", ValueOne, inTestStruct.ValueOne));
}
if (ValueTwo != inTestStruct.ValueTwo)
{
diffs.Add(new Diff("ValueTwo", ValueTwo, inTestStruct.ValueTwo));
}
if (ValueThree != inTestStruct.ValueThree)
{
diffs.Add(new Diff("ValueThree", ValueThree, inTestStruct.ValueThree));
}
return diffs;
}
}

public CompareStructsExample()
{
TestStruct t1 = new TestStruct();
t1.ValueOne = 1;
t1.ValueTwo = 8;
t1.ValueThree = 5;

TestStruct t2 = new TestStruct();
t2.ValueOne = 3;
t2.ValueTwo = 8;
t2.ValueThree = 7;

List diffs = t1.Compare(t2);
foreach (Diff d in diffs)
{
System.Console.WriteLine(d.ToString());
}
}

我想知道是否有一种方法可以通过某种序列化来执行此操作,或者这是否是实际查看哪些值已更改的唯一方法。即使有更好的方法来实现比较功能,我也会采用。

最佳答案

可以使用反射来完成。检查 FieldInfoPropertyInfo示例。

MSDN 示例(稍作修改):

    Type myType = typeof(TestStruct);

// Get the fields of TestStruct.
FieldInfo[] myFieldInfo =
myType.GetFields(
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

Console.WriteLine("\nThe fields of TestStruct are \n");

// Display the field information of TestStruct.
for(int i = 0; i < myFieldInfo.Length; i++)
{
Console.WriteLine("\nName : {0}", myFieldInfo[i].Name);
Console.WriteLine("Declaring Type : {0}", myFieldInfo[i].DeclaringType);
Console.WriteLine("IsPublic : {0}", myFieldInfo[i].IsPublic);
Console.WriteLine("MemberType : {0}", myFieldInfo[i].MemberType);
Console.WriteLine("FieldType : {0}", myFieldInfo[i].FieldType);
Console.WriteLine("IsFamily : {0}", myFieldInfo[i].IsFamily);
}

关于c# - 在 C# 中比较两个结构的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/983410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com