c# - C#动态设置值的方法
问题描述
我有一种在列表中搜索键的方法:
private static void Set<TTarget>(IList<Attributes> source, string key, TTarget target, Action<TTarget, string> setter) {
if (source[0].Key == key)
{
var value = source.FirstOrDefault();
setter(target, value.Value.ToString());
}
}
但是,如果在列表中找不到,有人可以建议一种方法来防止 Set 方法设置空值吗?目前,如果 Set 未找到任何值,则 Column1 设置为 null,但如果未找到,我想阻止 Set 设置值
public async Task Process(MyFile myFile){
var f = new MyFile();
Attributes = myFile.AttributesList.ToList();
// ignore if Set method not found a value
Set(Attributes, "column1", f, (target, val) => target.Column1 = val);
}
解决方案
您可以实现一个简单的检查,以确保在调用 setter 方法之前填充 value 变量:
private static void Set<TTarget>(IList<Attributes> source, string key, TTarget target, Action<TTarget, string> setter) {
if (source[0].Key == key)
{
var value = source.FirstOrDefault();
if(value == null || value == ""){
Console.WriteLine($"No value found for key {key}!");
} else {
setter(target, value.Value.ToString());
}
}
}
推荐阅读
- android - Android 媒体播放器 - DRM - Widevine
- python - 有没有办法从 1 开始 pandas add_prefix 列索引
- automated-tests - IBM AS400 上的自动远程登录测试
- typescript - 在 onLayout 事件中 React Native 的度量回调的 TypeScript 类型?
- php - Laravel 进度条被覆盖
- installation - 解决多库版本问题
- tomcat - 更新 Primefaces .xhtml 文件后先前保存的 Stacktrace 错误
- php - webklex laravel imap 未连接到 gmail
- python - 日期列的 MongoEngine 过滤器
- visual-studio-code - 如何在 devcontainer 中挂载 dotnet 用户机密?