delegate需要声明
、实例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace dotnetLearn.delegate_
{
// 这里声明委托 意思委托返回值是string
public delegate string GetString(string input);
public class Delegate01
{
public void DelegateTest01()
{
int x = 40;
// 这里都使用Lambda方式,委托创建实例一般有两种方式,一种是new,一种是直接赋值
// 创建实例方式1
GetString a = new GetString((input) =>
{
return input;
});
// 创建实例方式2,一般都使用第二种
GetString b = (input) =>
{
return input;
};
// 调用方式1
Console.WriteLine(a("atest"));
// 调用方式2
Console.WriteLine(b.Invoke("btest"));
Console.ReadKey();
}
}
}
内置的一个委托,用于委托有零或多个参数,没有返回值
的函数,只需要实例
即可,不需要声明了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace dotnetLearn.delegate_
{
public class Delegate02
{
public Action GetString = (input) =>
{
Console.WriteLine(input);
Console.ReadKey();
};
public void DelegateTest()
{
GetString("testAction");
}
}
}
内置的一个委托,用于委托有零或多个参数
,必须有返回值
的函数,只需要实例
即可,不需要声明了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace dotnetLearn.delegate_
{
public class Delegate03
{
// 参数是前面那个string,返回值是最后一个string
public Func GetString = (input) =>
{
return input;
};
public void DelegateTest()
{
Console.WriteLine(GetString("testFun"));
Console.ReadKey();
}
}
}
可以使用+ - 符号操作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace dotnetLearn.delegate_
{
public class Delegate04
{
public void test01()
{
Console.WriteLine("test01");
}
public void test02()
{
Console.WriteLine("test02");
}
public void DelegateTest()
{
Action test = test01;
test += test02;
test();
Console.ReadKey();
}
}
}
为委托提供了一种发布订阅机制,一种具有特殊签名的委托
下面是一个demo,猫来了,老鼠会跑的一个发布订阅案例
using System;
namespace dotnetLearn.delegate_
{
public class Delegate05
{
public void DelegateTest()
{
Cat cat = new Cat();
Mouse mouse = new Mouse("小白", cat);
Mouse mouse2 = new Mouse("小黑", cat);
cat.Come();
// 注意这个地方可以直接调用猫的委托方法,这样不安全
//cat.delegate_();
Console.ReadKey();
}
}
public class Cat
{
public void Come()
{
Console.WriteLine("我是喵喵喵,我来了");
if (delegate_ != null)
{
delegate_();
}
}
public Action delegate_;
}
public class Mouse
{
public string name;
public Mouse(string name, Cat cat)
{
this.name = name;
cat.delegate_ += run;
}
public void run()
{
Console.WriteLine("我是" + name + ",喵喵喵喵来了,快跑");
}
}
}
但是发现我们可以直接调用猫的委托方法(cat.delegate_())
,这样不安全,但是可以给public Action delegate_;
加上event
前缀,变成public event Action delegate_;
这样的话在类的外部就不能直接调用delegate_
了,但是在Cat类的内部中还是可以正常调用,就是这么一个标记的作用。
这里有疑惑的就是不在类的外部调用,那可以private Action delegate_;
但是这样的话Mouse中就不能cat.delegate_ += run;