.NET框架支持空操作语法或单 [英] .NET Framework supported empty action syntax or singleton

查看:178
本文介绍了.NET框架支持空操作语法或单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在现有框架的工作,有时你需要传递一个动作代表通常不执行任何操作的原始开发商增加了一个扩展点。例如:

When working with existing frameworks, sometimes you need to pass in an action delegate which performs no action usually an extension point added by the original developer. Example:

var anObject = new Foo(() => { });

和presumably的Foo对象会调用这个代表在一段时间。我的目标是消除使用{},因为我的风格决定了{}需要对自己的,独立的线,我有点强迫症和讨厌冗长的,如果我没有要。

And presumably the Foo object will call this delegate at some time. My goal here is to eliminate the use of { }, because my style dictates that { } need to be on their own, and separate lines, and I'm a bit OCD and hate being verbose if I don't have to be.

在与返回值的动作时,这是简单的enough-你可以提供一个前pression,而不是一个声明(从而消除了支撑。)例如:

When dealing with an action which returns a value, this is simple enough- you can provide an expression instead of a statement (thus eliminating the braces.) Example:

var anObject = new Foo(() => string.Empty);

所以,我认为这个问题是两部分...

So, I suppose the question is two parts...

.NET是否有任何形式的默认空的动作? 是否有语法糖提供的空EX pression到一个lambda,比{}?

Does .NET have any sort of default empty action? Is there syntactic sugar for providing an empty expression to a lambda, other than { }?

目前的解决方案我倾向于是定义在preceding分配的委托,以避免使用拉姆达EX pressing一个函数调用里面。

The current solution I'm leaning towards is to define the delegate in a preceding assignment to avoid having to use the lambda expressing inside a function invocation.

推荐答案

没有什么内置的,我是知道的。

There's nothing built-in that I'm aware of.

您可以只定义委托的一次的作为辅助单:

You could just define the delegate once as a helper singleton:

var anObject = new Foo(NoOpAction.Instance);

// ...

var anotherObject = new Bar(NoOpAction.Instance);

// ...

public static class NoOpAction
{
    private static readonly Action _instance = () => {};

    public static Action Instance
    {
        get { return _instance; }
    }
}

和,因为你正好在每次使​​用 NoOpAction.Instance 在你的程序的时候递给相同的委托,你还节省的(诚然小)成本创建和垃圾收集多个代表们都做同样的事情。

And because you're handed exactly the same delegate every time you use NoOpAction.Instance throughout your program, you're also saving on the (admittedly small) cost of creating and garbage-collecting multiple delegates that all do the same thing.

这篇关于.NET框架支持空操作语法或单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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