C#: create a do-nothing Action on class instantiation(C#:在类实例化上创建一个无操作动作)
问题描述
我有一个类,用户可以将 Action 传递给(或不传递给).
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 传递给 Action 的基类.但是,与此同时,我不想强迫我的用户传入 Action.相反,我希望能够即时创建无所事事"动作.
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 =>匿名表达式主体.在这种情况下,anonymous-expression-body 是 expression 或 block.你不能有一个空的表达式,所以你不能用 expression 来表示一个空的方法体.因此,你必须使用一个 block 在这种情况下你可以说 { } 来表示一个 block 有一个空的 statement-列表,因此是空的主体.
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.
这是另一种思考方式,您可以用这种方式自己发现这一点.Action<T> 是一个接受 T 并返回 void 的方法.您可以通过非匿名方法或匿名方法定义 Action<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 表达式.因此,我们丢弃 private void MyAction 并用 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#:在类实例化上创建一个无操作动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#:在类实例化上创建一个无操作动作
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
