gpt4 book ai didi

c# - 重复方法调用模型的不同属性

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:25 25 4
gpt4 key购买 nike

是否可以简化这段代码?我正在将值列表中的数据转换为同一个对象。在每种方法中,被求和的属性都会发生变化。

属性每次都遵循相同的命名约定(paiospa)后跟(InUseSuportInUse ).我知道在 JavaScript 中我可以生成字符串并评估字符串,但据我所知在 C# 中没有类似的东西。

public class CompanyLicValues
{
public int Paios;
public int Papc;
public int Paplus;
public int Eis;
public int Pd;
public int Dropoff;

public CompanyLicValues SumInUse(List<vwCompany> companies)
{
Paios = companies.Sum(x => x.paiosInUse); //<<<The property being summed changes
Papc = companies.Sum(x => x.papcInUse); //<<<The property being summed changes
....
return this;
}

public CompanyLicValues SumSupportUsed(List<vwCompany> companies)
{
Paios = companies.Sum(x => x.paiosSupportInUse); //<<<The property being summed changes
Papc = companies.Sum(x => x.papcSupportInUse); //<<<The property being summed changes
...
return this;
}
}

最佳答案

您可以使用反射来获取属性,然后找到要使用的属性

public class CompanyLicValues
{
public int Paios { get; private set; }
public int Papc { get; private set; }


public CompanyLicValues SumInUse(List<VwCompany> companies)
{
SumDynamically(companies, "InUse");
return this; return this;
}

public CompanyLicValues SumSupportUsed(List<VwCompany> companies)
{
SumDynamically(companies, "SupportInUse");
return this;
}

private void SumDynamically(IReadOnlyCollection<VwCompany> companies, string propertySuffix)
{
Paios = SumProperty(companies, $"{nameof(Paios)}{propertySuffix}");
Papc = SumProperty(companies, $"{nameof(Papc)}{propertySuffix}");
}

private static int SumProperty(IEnumerable<VwCompany> companies, string propertyName)
{
var properties = typeof(VwCompany).GetProperties(); //cache properties
var p = properties.FirstOrDefault(x => x.Name == propertyName && x.GetMethod.ReturnType == typeof(int));
if (p is null) throw new Exception("Property Not found");

return companies.Sum(x => (int)p.GetValue(x));
}
}

关于c# - 重复方法调用模型的不同属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57154199/

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