首页 > 解决方案 > 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); 
}

标签: c#c#-4.0

解决方案


您可以实现一个简单的检查,以确保在调用 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());
        }
    }
}

推荐阅读