在C#可选代表 [英] Optional delegates in C#

查看:85
本文介绍了在C#可选代表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是两个扩展方法一个简单的例子重载

This is a simple example of two extension methods overloads

public static class Extended 
{
    public static IEnumerable<int> Even(this List<int> numbers)
    {
        return numbers.Where(num=> num % 2 == 0);
    }

    public static IEnumerable<int> Even(this List<int> numbers, Predicate<int> predicate)
    {
        return numbers.Where(num=> num % 2 == 0 && predicate(num));
    }
}

我希望能够将它们合并成一个,通过设置代理是可选的:

I'd like to be able to merge them into one, by setting a delegate to be optional:

public static class Extended 
{
    public static IEnumerable<int> Even(this List<int> numbers, Predicate<in> predicate = alwaysTrue)
    {
        return numbers.Where(num=> num % 2 == 0 && predicate(num));
    }

    public static bool alwaysTrue(int a) { return true; }
}

不过,编译器会引发错误:

However, compiler throws an error:

有关'predicate默认参数值必须是一个编译时常

Default parameter value for 'predicate' must be a compile-time constant

我看不到我的alwaysTrue功能怎么不是恒定的,但是,嘿,编译器知道更好:)

I don't see how my alwaysTrue function is not constant, but hey, compiler knows better :)

有没有什么办法,使委托参数可选?

Is there any way to make the delegate parameter optional?

推荐答案

这不是恒定的,因为你已经从一个方法组创建一个委托......这不是一个编译时尽可能的C#语言的关注不断。

It's not constant because you've created a delegate from a method group... that's not a compile-time constant as far as the C# language is concerned.

如果你不介意的滥用的含义略有你可以使用:

If you don't mind abusing the meaning of null slightly you could use:

private static readonly Predicate<int> AlwaysTrue = ignored => true;

public static List<int> Even(this List<int> numbers,
                             Predicate<int> predicate = null)
{
    predicate = predicate ?? AlwaysTrue;
    return numbers.Where(num=> num % 2 == 0 && predicate(num));
}

(您的可能的仍然让 AlwaysTrue 的方法和使用方法组转换,但上面的方法是的非常轻微通过创建委托实例只是一次更有效。)

(You could still make AlwaysTrue a method and use a method group conversion, but the above approach is very slightly more efficient by creating the delegate instance just once.)

这篇关于在C#可选代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆