【问题标题】:C# dynamic method for setting valueC#动态设置值的方法
【发布时间】:2023-04-04 23:07:01
【问题描述】:

我有一个在列表中搜索键的方法:

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); 
}

【问题讨论】:

  • if(value != null) { setter(...); } 怎么样?

标签: c# c#-4.0


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 2020-05-30
    • 2012-06-10
    • 2019-03-13
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多