在C#中,是否有一种方法可以忽略委托中的参数,以使代码更清晰?

huangapple go评论57阅读模式
英文:

Is there a way to ignore argument in delegate, for cleaner code in C#

问题

我有一个 Action<string, string>,但在订阅的方法中,我不需要那些数据。我能在不传递这些参数的情况下订阅方法吗?我不想要无用的参数。但是由于委托,我不能只是把那个动作的数据设为空,因为它在其他脚本中需要。

public Action<string, string> onKill;
其他脚本

health.OnKill += AddArmor; // 在这里,我想让AddArmor不带参数,但是因为委托的原因,我不能这样做
英文:

I have Action&lt;string, string&gt;, but in subscribed method I don't need that data. Can I subscribe method without those arguments somehow? I just don't want to make useless arguments. And I cant just make that action's data blank, since it's needed in other script

public Action&lt;string, string&gt; onKill;

Other script

health.OnKill += AddArmor; // Here I want to make AddArmor argumentless, but because of delegate, I can&#39;t

答案1

得分: 1

通常的做法是将其包装在一个小型 lambda 表达式中:

health.OnKill += (x, y) => AddArmor();

匿名函数的旧语法允许省略 xy

health.OnKill += delegate { AddArmor(); };
英文:

The usual thing to do is to wrap it in a small lambda:

health.OnKill += (x, y) =&gt; AddArmor(); 

The old syntax for anonymous function offers to leave out x and y altogether:

health.OnKill += delegate { AddArmor(); };

答案2

得分: 1

在C#中,你可以使用下划线(_)符号在委托中忽略参数,就像你的情况下这样。是的,你可以使用lambda表达式在订阅方法到委托时忽略参数。

health.OnKill += (_, __) => AddArmor();

在这里,lambda表达式通过将参数分别赋值给_和__,从Action<string, string>委托中忽略了两个参数。然后,AddArmor方法被调用时不带任何参数。

英文:

C#, you can use the _ (underscore) symbol to ignore arguments in delegates HERE in your case Yes, you can use a lambda expression to ignore the arguments when subscribing the method to the delegate.

health.OnKill += (_, __) =&gt; AddArmor();

Here, the lambda expression ignores both arguments from the Action<string, string> delegate by assigning them to _ and __ respectively.
The AddArmor method is then invoked without any arguments.

huangapple
  • 本文由 发表于 2023年2月6日 15:34:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75358473.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定