【发布时间】:2012-11-14 06:39:17
【问题描述】:
我想编写一个可以在将值插入列表之前完成一些检查的函数。 例如:
class Person {
public string Name { get; set; }
public int Value { get; set; }
public Guid Id { get; set; }
}
-------
var persons = new List<Person>();
// add a new person if John doesn't exist
persons.AddIf(s => !s.Name.Equals("John"), new Person { ... });
----
public static void AddIf(this List<T> lst, Func<T, bool> check, T data)
{
// how can I use the Func 'check' to check if exist an object with the
// information that the client wrote and, if not exists, insert the new value
// into the list???
if ( check )
}
我如何使用 Func 'check' 来检查是否存在具有客户端写入信息的对象,如果不存在,则将新值插入列表中?
【问题讨论】:
-
请注意,在您的示例中,无论谓词结果如何,您都会创建 Person 对象。如果您不打算在检查失败时使用此对象,您可能应该更改方法的签名,以便仅在需要时创建 Person 对象。
-
@PanosRontogiannis 很可能只是一个虚拟变量 OP 放在那里。他很可能已经有一个实例要添加..
标签: c# generics lambda extension-methods