gpt4 book ai didi

c# - 常见模式,在这里我试图简化它以减少重复

转载 作者:太空狗 更新时间:2023-10-30 01:30:48 26 4
gpt4 key购买 nike

以下方法中的所有这些 if 条件都具有相似的模式,想出一个通用方法来减少此方法中的重复有什么想法吗?

    public override Func<JObject, dynamic, string> version => (jobject, parameters) =>
{
bool hasValidObject = false;

if (jobject["Version1"] != null)
{
_radio.Version1 = new VersionInfo(jobject["Version1"].Value<string>());
hasValidObject = true;
}

if (jobject["Version2"] != null)
{
_radio.Version2 = new VersionInfo(jobject["Version2"].Value<string>());
hasValidObject = true;
}

if (jobject["Version3"] != null)
{
_radio.Version3 = new VersionInfo(jobject["Version3"].Value<string>());
hasValidObject = true;
}

if (jobject["Version4"] != null)
{
_radio.Version4 = new VersionInfo(jobject["Version4"].Value<string>());
hasValidObject = true;
}

if (jobject["Version6"] != null)
{
_radio.Version6 = new VersionInfo(jobject["Version6"].Value<string>());
hasValidObject = true;
}

if (hasValidObject)
{
return GenerateSuccess();
}

return GenerateUnsuccessful( try again.");
};

最佳答案

一种方法是使用反射和循环

public override Func version => (jobject, parameters) => 
{
bool hasValidObject = false;
for (int i = 1; i<7;i++)
{
hasValidObject = this.SetVersionInfo(i) || hasValidObject;
}

if (hasValidObject)
{
return GenerateSuccess();
}

return GenerateUnsuccessful( "try again.");
};


private bool SetVersionInfo(int i)
{
if (jobject["Version" + i] == null) return false;

_radio.GetType().GetProperty(propName)
.SetValue(_radio, new VersionInfo(jobject["Version" + i].Value<string>()));
return true;
}

另一种方法是创建一个 Dictionary<int,VersionInfo> Versions在你的_radio类然后你不需要反射:

private bool SetVersionInfo(int i)
{
if (jobject["Version" + i] == null) return false;

_radio.Versions[i] = new VersionInfo(jobject["Version" + i].Value<string>());
return true;
}

关于c# - 常见模式,在这里我试图简化它以减少重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42961724/

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