c#-将方法分配给委托,委托中参数比方法多
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c#-将方法分配给委托,委托中参数比方法多,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1761字,纯文字阅读大概需要3分钟。
内容图文
![c#-将方法分配给委托,委托中参数比方法多](/upload/InfoBanner/zyjiaocheng/658/330c83614dfe4adf9d85265aefd40f66.jpg)
这个问题已经在这里有了答案: > Can a method be attached to a delegate with predefined parameters? 2个
我有一个委托,需要很多参数,例如:
public delegate void MyDelegate(float thereAre, int lotsOf, string parametersIn, int thisDelegate);
public MyDelegate theDelegateInstance;
这很烦人,因为Visual Studio 2010没有任何自动完成功能来帮助方法匹配委托签名.我基本上希望能够编写一种只接受委托参数中的一些(或不接收)参数,而忽略其他参数的方法,因为该方法无论如何都不会使用它们.
theDelegateInstance += delegate()
{
Debug.Log("theDelegateInstance was called");
};
要么
theDelegateInstance += delegate(float thereAre, int lotsOf)
{
if(thereAre > lotsOf) Debug.Log("thereAre is way too high");
};
我发现我可以使一个方法接受一个委托,返回一个MyDelegate,调用它的方式如下:
public delegate void VoidMethod();
public static MyDelegate ConvertToMyDelegate(VoidMethod method)
{
return delegate(float thereAre, int lotsOf, string parametersIn, int thisDelegate)
{
method();
};
}
但这需要我为每个不同的转换声明一个静态方法.
我只是发现我可以不用任何参数就能完成我的第一个示例,以达到所需的结果:
theDelegateInstance += delegate//Notice that there are no brackets here.
{
Debug.Log("theDelegateInstance was called");
};
但这仅适用于不带参数的内联方法.如果我想像第二个示例一样使用其中一个参数,则需要全部使用.
解决方法:
您可以随时使用lambdas进行操作.
您可以通过两种方式进行操作-使用要调用的两个示例函数:
第一种方法-创建方法,然后直接调用它:
void FirstFunction(float thereAre, int lotsOf)
{
if(thereAre > lotsOf)
Debug.Log("thereAre is way too high");
}
并以这种方式调用它:
theDelegateInstance += (t, l, p, td) => FirstFunction(t, l);
第二种方法-无需创建函数即可直接进行调用:
theDelegateInstance +=
(t, l, p, td) => Debug.Log("theDelegateInstance was called");
内容总结
以上是互联网集市为您收集整理的c#-将方法分配给委托,委托中参数比方法多全部内容,希望文章能够帮你解决c#-将方法分配给委托,委托中参数比方法多所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。