0
点赞
收藏
分享

微信扫一扫

【小5聊】C#基础之内置和自定义委托的简单使用


最近一段时间都在面试,最大的感概就是,没有掌握太多核心的技术,所以随着年龄的增长,其实优势就没有了,自然得不到技术官或者总监的认可。

不管如何,学习肯定是不能停的,由于个人理解方面会比较差,所以需要后天很多实战进行积累来辅助我的理解,在这个阶段已经开始慢慢多很多知识点的回顾加深了一定的理解,从而能够对框架和编程更加有帮助

1、什么是委托

这个在面试的时候,被问到的概率也会很高

什么是委托呢? 简单的理解就是,委托是执行一个方法或者某个方法体,和前端js的callback类似

1)委托是一个类

关键词:delegate

有点类似定义了一个interface接口方式一样,先定义不实现

【小5聊】C#基础之内置和自定义委托的简单使用_c#

2)委托属于一个引用类型

自然就拥有引用类型的特点,不会保存实际值,而是保存存储在托管堆中的对象的引用,保存函数的引用

3)委托定义了方法的类型

能够将方法当作参数在另一个方法里传递,可以避免在方法里使用大量if-else或者switch

4)委托最大特点是能够最大化的扩展

5)委托类型安全属性

.NET中的委托是类型安全的,委托会检测它所保存的函数引用是否和声明的委托匹配。

2、内置委托Action

假设有如下txt文本内容,需要读取出来,然后通过分组将题目和答案分开

【小5聊】C#基础之内置和自定义委托的简单使用_类型安全_02

代码如下

public void Temp()
{
try
{
string path = @"C:\86_svn\question_collect\files";
string content = Get(path, "data");
string[] list = content.Split("\r\n");

foreach (string item in list)
{
if (string.IsNullOrEmpty(item)) continue;
string item_value = item.Replace("(", "(");

string question_content = "";
string answer_value = "";
string[] arr = item_value.Split('(');

// 定义内置委托
Action action1 = new Action(() =>
{
question_content = arr[0];
if (question_content.Split('.').Length > 0)
{
question_content = question_content.Split('.')[1];
}

for (int i = 1; i < arr.Length; i++)
{
answer_value += arr[i];
}

answer_value = answer_value.TrimEnd(')').TrimEnd(')');
});

if (arr.Length > 1)
{
action1();
}
else
{
arr = item_value.Split('(');
if (arr.Length > 1)
{
action1();
}
}
}
}
catch (Exception exception)
{

}
finally
{

}
}
#endregion

public static string Get(string path_value, string file)
{
string str = "";

try
{
string pathFile = path_value;
string fileName = "/" + file + ".txt";

using (StreamReader r = new StreamReader(pathFile + fileName))
{
str = r.ReadToEnd();
}
}
catch (Exception ex)
{
LmyLogHelper.Error(ex);
}

return str;
}

 3、自定义委托

【小5聊】C#基础之内置和自定义委托的简单使用_引用类型_03

 

public delegate int MyDelegate(int a);

public void Temp()
{
MyDelegate tt = new MyDelegate((int a) =>
{
int b = a + 5;

return b;
});
int c = tt(6);
}

举报

相关推荐

0 条评论