[C#] 如何将字典的value赋值为函数

0. 应用场景

   将用户上传到的图片, 根据保密程度有三种处理方式,1.放置于服务器上,可直接访问, 2.放置于服务器上,但需要从数据库查询路径,3.将文件写入MongoDB中

1. Nodejs操作思路

  因为本人毕业先做的Nodejs后端开发, 一些思路固定了,习惯了之前的编程方法,再转移到现用语言中。   

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function saveNormalFile() {
  console.log("放置于服务器上,可直接访问")
}
 
function savePathToDB() {
  console.log("放置于服务器上,但需要从数据库查询路径")
}
 
function saveFileToDB() {
  console.log("将文件写入MongoDB")
}
 
const methodMap = {
  0:saveNormalFile,
  1:savePathToDB,
  2:saveFileToDB
};
 
const file = {
  level:0,
  data:"二进制流",
  name:"2333.png",
  user:"aha"
};
 
// 根据文件类型,选择存储函数
methodMap[file.level]();

    程序输出: 放置于服务器上,可直接访问

   switch case的时间复杂最坏情况为n, 平均为 (1+2+3+4+ . . . . . +n) / n  = (  (1+n) * n/2 ) / n = (1+n)/ 2, 并且代码的分支语句太多,不易维护

2. 虽然对C#不熟练,但是肯定可以解决,传递函数的方式就是指针,使用引用类型delegate,最终结果如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class DictionaryDelegate
{
    public delegate void Method();  // 我的函数没有参数和返回, 可根据自己的需求修改
 
    static Method saveNormalFile = () =>
    {
        Console.WriteLine("放置于服务器上,可直接访问");
    };
 
    static Method savePathToDB = () =>
    {
        Console.WriteLine("放置于服务器上,但需要从数据库查询路径");
    };
 
    static Method saveFileToDB = () =>
    {
        Console.WriteLine("将文件写入MongoDB");
    };
 
    Dictionary<string, Method> MethodDictionary = new Dictionary<string, Method>
        {
            {"0", saveNormalFile},
            {"1", savePathToDB},
            {"2", saveFileToDB},
        };
    public DictionaryDelegate()
    {
        MethodDictionary["0"]();
    }
}

3. 如果不使用简单的lamda函数,也可正常调用委托函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class DictionaryDelegate
{
    public delegate void Method();  // 我的函数没有参数和返回, 可根据自己的需求修改
    public void saveNormalFile()
    {
        Console.WriteLine("放置于服务器上,可直接访问");
    }
 
    public DictionaryDelegate()
    {
        Dictionary<string, Method> MethodDictionary = new Dictionary<string, Method>
        {
            {"0", new Method(saveNormalFile) }
        };
        MethodDictionary["0"].BeginInvoke(null, null);
    }
}

  

  

 

 

posted @   戚戚绛绛  阅读(614)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示