3

我想要一个“谓词”(它在引号中,因为我不知道正确的词),它根据条件返回对象的不同字段。我希望一个简短的例子可以说明。

 Predicate<MyClass> predicate
 if (condition1)
    predicate = x => x.Field1;
 else if (condition2)
     predicate = x => x.Field2;
foreach(vat item in ListOfItems)
{
    predicate(item) = someValue;//Here I am changing the value of that field.
}
4

2 回答 2

5

您正在寻找的通用术语是"delegate"。虽然你不能直接predicate(item) = someValue;在 C# 中做类似的事情,但你可以使用Actions和/或Funcs来做你想做的事情。获取值是更常用的做事方式,例如 LINQ 的Select实现方式如下:

public static IEnumerable<TResult> Select<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, TResult> selector
)
{
    foreach (var item in source)
        yield return selector(item);
}

并且像这样使用:

myList.Select(x => x.Field1);

你可以定义一些可以设置属性的东西,像这样:

public static void SetAll<TSource, TProperty>(
    this IEnumerable<TSource> source,
    Action<TSource, TProperty> setter,
    TProperty someValue // example for how to get the value
)
{
    foreach (var item in source)
    {
        setter(item, someValue);
    }
}

并像这样使用它:

myList.SetAll((x, value) => x.Property1 = value, "New value");
// all Property1s are now "New value"

或者像你的例子:

Action<MyClass, string> predicate;
if (condition1)
    predicate = (x, value) => x.Property1 = value;
else
    predicate = (x, value) => x.Property2 = value;
foreach (var item in ListOfItems)
{
    predicate(item, someValue);
}
于 2013-11-02T16:35:11.033 回答
0

好吧,我决定这样做:

Func<MYClass, DateTime> f = null;
if (Condition1)
    f = x => x.Field1;
else if (condition2)
   f = x => x.Field2;
于 2013-11-02T17:09:13.407 回答