黑马程序员技术交流社区
标题: 委托中传方法时候的一个小问题?? [打印本页]
作者: 赵威 时间: 2013-4-24 16:21
标题: 委托中传方法时候的一个小问题??
本帖最后由 赵威 于 2013-4-25 16:52 编辑
namespace
{
class Program
{
static void Main(string[] args)
{
Class1 c1 = new Class1();
string[] str={"mingren","jiuxinnai","shuimen"};
c1.ChangeString(str,M1);
foreach (var items in str)
{
Console.WriteLine(items);
}
Console.ReadKey();
}
static string M1(string str)
{
return "=" + str + "=";
}
static string M2(string str)
{
return str.ToUpper();
}
}
public class Class1
{
public void ChangeString(string[] str, ModifyStringDelegate md)
{
for (int i = 0; i < str.Length; i++)
{
str = md(str);
}
}
}
public delegate string ModifyStringDelegate(string str);
}
file:///C:/Users/Administrator/AppData/Local/youdao/ynote/images/AF8BC0AB9F444A929AAF4F58177EAB99/BE55859A7E4F4282800F49729B80F902.jpg
截图:
这里本来应该new一个委托对象的,然后将方法当参数传到程序中,但为什么没有new,直接把方法传到第二个参数的位置上,也能出结果,这是为什么??
作者: 许庭洲 时间: 2013-4-24 21:29
// Declare a delegate
//委托 Del 和关联的方法MultiplyNumbers 具有相同的签名
//C# 中,命名方法是对委托进行实例化的唯一方式。但是,在不希望付出创建新方法的系统开销时,C# 使您可以对委托进行实例化,并立即指定委托在被调用时将处理的代码块。这些被称为匿名方法。
delegate void Del(int i, double j);
class MathClass
{
staticvoid Main()
{
MathClass m = new MathClass();
// Delegate instantiation using"MultiplyNumbers"
Del d = m.MultiplyNumbers;
//Invoke the delegate object.
System.Console.WriteLine("Invoking the delegate using'MultiplyNumbers':");
for (int i = 1; i <= 5; i++)
{
d(i, 2);
}
}
//Declare the associated method.
voidMultiplyNumbers(int m, double n)
{
System.Console.Write(m * n + " ");
}
}
输出
Invoking the delegate using 'MultiplyNumbers':
2 4 6 8 10
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |