简体   繁体   English

在一个函数参数中使用多个谓词?

[英]Use more than one predicate in a function parameter?

I have a class that builds a url with query string parameters and so on. 我有一个用查询字符串参数构建url的类,依此类推。 The class has a method: Url() which returns the complete url composed from the class properties and another method: UrlNew() which allows passing a predicate as parameter for the replacement of the value of one of the properties and THEN Returns the modified URL. 该类具有一个方法:Url()返回由类属性组成的完整url;另一个方法:UrlNew()允许传递谓词作为参数以替换属性之一的值,然后返回修改的URL 。 Now, I need to modify this function to use TWO parameters, both predicates. 现在,我需要修改此函数以使用两个谓词两个参数。 How do I do that? 我怎么做? I tried modifying the method's parameters as a List of predicates but I probably am not doing something right: 我尝试将方法的参数修改为谓词列表,但是我可能做的不正确:

My OLD UrlNew() method looked like this: 我的OLD UrlNew()方法如下所示:

public static string Url() (Action<LGUrlBuilder> predicate)
    {
        var instance = new LGUrlBuilder();
        if (predicate != null) predicate(instance);
        return instance.BuildUrl();
    }

My NEW UrlNew() method looks like this: 我的NEW UrlNew()方法如下所示:

public static string UrlNew(List<Action<LGUrlBuilder>> predicateList)
    {
        var instance = new LGUrlBuilder();
        if (predicateList != null && predicateList.Count > 0)
        {
            foreach (Action<LGUrlBuilder> predicate in predicateList)
            {
                if (predicate != null) predicate(instance);
            }
        }

        return instance.BuildUrl();
    }

This compiles just fine but when I run it, using it in ASPX gives me this error: 这样编译就可以了,但是当我运行它时,在ASPX中使用它会给我这个错误:

CS1660: Cannot convert lambda expression to type 'System.Collections.Generic.List<System.Action<public_site.Library.LG.LGUrlBuilder>>' because it is not a delegate type

I am a C# beginner and I am sure I am doing something completely wrong. 我是C#初学者,我确定自己做的事情完全错误。 Any advice would help. 任何建议都会有所帮助。 Thanks! 谢谢!

Don't modify the function itself. 不要修改函数本身。 Modify the method call like this: 像这样修改方法调用:

UrlNew(x => { func1(x); func2(x); });

But if you really want to take arbitrary number of delegate instances as arguments, try modifying it like: 但是,如果您确实想将任意数量的委托实例作为参数,请尝试按以下方式进行修改:

public static void UrlNew(params Action<LGUrlBuilder>[] list) {
    // ... do what you're already doing in the second snippet ...
}

You can call it like: 您可以这样称呼它:

UrlNew(x => firstthing(), x => secondthing(x), thirdthing);

Side note: An Action<T> is not called a predicate. 旁注: Action<T>不称为谓词。 A predicate returns a boolean value. 谓词返回布尔值。

How about using the overloaded Action<T1,T2> delegate which accepts 2 parameters. 如何使用接受2个参数的重载Action<T1,T2>委托。 If you are looking to use a predicate instead which expects a boolean return value then use Func<T1,T2,bool> instead. 如果您要使用期望布尔返回值的谓词,请改用Func<T1,T2,bool>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM