英文:
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<string, string>
, 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<string, string> onKill;
Other script
health.OnKill += AddArmor; // Here I want to make AddArmor argumentless, but because of delegate, I can't
答案1
得分: 1
通常的做法是将其包装在一个小型 lambda 表达式中:
health.OnKill += (x, y) => AddArmor();
匿名函数的旧语法允许省略 x
和 y
:
health.OnKill += delegate { AddArmor(); };
英文:
The usual thing to do is to wrap it in a small lambda:
health.OnKill += (x, y) => 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 += (_, __) => 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论