gpt4 book ai didi

c# - 遍历定义的具体类型的成员?

转载 作者:行者123 更新时间:2023-11-30 18:20:11 27 4
gpt4 key购买 nike

我正在跨数据库(大约有 20 个字段)进行比较,并且我已经定义了一个具体类型来处理比较。

如果比较失败,我想遍历 catch block 中的各个项目并向用户提供错误列表。下面,我通过前几个变量手动完成了它。有没有更有效的方法来遍历所有 20 个字段?我从 foreach (Object objectItem .. 但不确定这是否是正确的方法开始。

有什么想法或急需的指导吗?

      try { 

CollectionAssert.IsSubsetOf(orgs, members, "Error Matching testlist Fields");

}

catch
{
//OrgID
var sourceOrgID = orgs.Select(o => o.OrgID);
var destOrgID = members.Select(o => o.OrgID);
var errorList1 = sourceOrgID.Except(destOrgID);
string failedTests = null;
failedTests = string.Join("\n", errorList1);
Assert.IsTrue(0 == failedTests.Length, "The following Org IDs are not contained in the source: \n" + failedTests);

//DealerCode
var sourceDealerCode = orgs.Select(o => o.DealerCode);
var destDealerCode = members.Select(o => o.DealerCode);
var errorList2 = sourceDealerCode.Except(destDealerCode);
failedTests = null;
failedTests = string.Join("\n", errorList2);
Assert.IsTrue(0 == failedTests.Length, "The following Dealer Codes are not contained in the source: \n" + failedTests);


//orgkey
var sourceOrgKey = orgs.Select(o => o.OrgKey);
var destOrgKey = members.Select(o => o.OrgKey);
var errorList3 = sourceOrgKey.Except(destOrgKey);
failedTests = null;
failedTests = string.Join("\n", errorList3);
Assert.IsTrue(0 == failedTests.Length, "The following Org Keys are not contained in the source: \n" + failedTests);

最佳答案

你需要反射(reflection)才能做到这一点:

Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
GetColumn(orgList,property.Name);
}



var names = items.Select(x => x.GetType().GetProperty("prpname").GetValue(x));


public IEnumerable<object> GetColumn(List<Item> items, string columnName)
{
var values = items.Select(x =>
x.GetType().GetProperty(columnName).GetValue(x));//u can put your test code heere and you can loop it through object properties
}

您可以创建一个列表来存储 rslt 并将结果添加到列表中,否则您可以将输出写入日志文件

关于c# - 遍历定义的具体类型的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37708596/

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