C#:创建类的实例化一个什么都不做动作 [英] C#: create a do-nothing Action on class instantiation

查看:94
本文介绍了C#:创建类的实例化一个什么都不做动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,用户可以通过一个操作进(或没有)

I have a class that the user can pass an Action into (or not).

public class FooClass<T> : BaseClass<T>
{
    public FooClass()
        : this((o) => ()) //This doesn't work...
    {
    }

    public FooClass(Action<T> myAction)
        : base(myAction)
    {
    }
}



基本上,我不能为null传递到了动作。但是,在同一时间,我不想强​​迫我的用户在动作通过。相反,我希望能够以动态创建一个什么也不做的行动。


Basically, I can't pass null into my base class for the Action. But, at the same time I don't want to force my user to pass in an Action. Instead, I want to be able to create a "do-nothing" action on the fly.

推荐答案

您想说

this(t => { })

认为它这样。您需要 T =>匿名表达体。在这种情况下,匿名表达体表达式。你不能有一个空的表现,所以你不能表明空的方法体与表达式。因此,你必须使用一个在这种情况下,你可以说 {} 来表示一个有一个空的语句列表,因此是空的身体。

Think of it like this. You need t => anonymous-expression-body. In this case, anonymous-expression-body is an expression or a block. You can't have an empty expression so you can't indicate an empty method body with an expression. Therefore, you have to use a block in which case you can say { } to indicate the a block has an empty statement-list and is therefore the empty body.

有关详细信息,请参阅语法规范,附录b中。

For details, see the grammar specification, appendix B.

和这里的另一种方式来想起来,这是,你可以用它来发现这个对自己的一种方式。一个动作< T> 是发生在一个方法 T 并返回无效。您可以定义一个动作< T>通过非匿名方式或通过匿名方式。您正在试图找出如何使用匿名方式(或者更确切地说,一个非常特殊的匿名方法,即lambda表达式)做到这一点。如果你想通过一个非匿名的方法来做到这一点,你会说

And here's another way to think of it, which is a way that you could use to discover this for yourself. An Action<T> is a method that takes in a T and returns void. You can define an Action<T> via an non-anonymous method or via an anonymous method. You are trying to figure out how to do it using an anonymous method (or rather, a very special anonymous method, namely a lambda expression). If you wanted to do this via a non-anonymous method you would say

private void MyAction<T>(T t) { }

,然后你可以说

this(MyAction)

它采用的方法组的概念。但是现在你想将这个转换为一个lambda表达式。所以,我们只是采取的方法体,并使其成为lambda表达式。因此,我们扔掉私人无效MyAction< T>(T T)并将其替换为 T => 复制逐字方法体 {}

which uses the concept of a method group. But now you want to translate this to a lambda expression. So, let's just take that method body and make it a lambda expression. Therefore, we throw away the private void MyAction<T>(T t) and replace it with t => and copy verbatim the method body { }.

this(t => { })

景气

这篇关于C#:创建类的实例化一个什么都不做动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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