DelegateSeries/Study.DelegateSeries.Core/声明委托.md

69 lines
2.0 KiB
Markdown

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 声明委托
> 委托三步曲:**声明**委托 -> **实例化**委托 -> **调用**委托;
> 声明委托是使用委托的第一步。
委托通常在三个地方声明:
+ 名字空间:
> 可见范围程序集内或引用了程序集无需使用using引入即可使用
``` CSharp
using System;
//命名空间同级调用方只需要引用定义类库就能使用不需要使用Uing语句引入定义委托的命名空间。
public delegate string GlobalDelegate();
namespace DelegateDemo
{
......
}
```
+ 类同级:
> 委托本质是和一样的自定义类型,和类同级。所以,能声明类的地方也能声明委托,可见范围与类相似。
``` CSharp
using System;
namespace DelegateDemo
{
//类同级:最常用和推荐的,可见范围与使用方法与类相同。
public delegate string ClassLevelDelegate();
public class OtherClass
{
......
}
}
```
+ 类内部,与类中方法同级:
> 可见范围与类内方法相同;调用时,要先指定类:类名.委托名
``` CSharp
using System;
namespace DelegateDemo
{
public class DemoClass
{
//类内部方法同级:可见范围与使用方法与类中方法相似,调用方须先调用类,后再调用委托。
public delegate string InsideDelegate();
//类内方法
public string GetName()
{
//方法体内:不允许定义委托
return "DeclearDelegate";
}
/// <summary>
/// 小写字串
/// </summary>
public static string ConvertToLower(string source)
{
return source.ToLower();
}
}
}
```
文件说明:
> 可以与其它类在同一个.cs文件里也可以单独成一个文件或集中到一个文件中便于管理。