首页
学习
活动
专区
圈层
工具
发布

将JavaScript移植到C# (函数存储在数组中)

JavaScript 函数数组移植到 C# 的解决方案

基础概念

在 JavaScript 中,函数是一等公民,可以像普通变量一样存储在数组中。这种模式常用于回调函数集合、插件系统或事件处理器管理。C# 作为静态类型语言,处理方式有所不同,但可以通过委托(delegate)实现类似功能。

主要差异

  1. 类型系统:JavaScript 是动态类型,C# 是静态类型
  2. 函数表示:JavaScript 使用函数对象,C# 使用委托类型
  3. 执行上下文:JavaScript 有 this 绑定,C# 需要显式处理

解决方案

1. 使用委托数组

代码语言:txt
复制
using System;
using System.Collections.Generic;

class Program
{
    // 定义委托类型
    delegate void MyDelegate(string message);
    
    static void Main()
    {
        // 创建委托数组
        MyDelegate[] functions = new MyDelegate[]
        {
            message => Console.WriteLine("Function 1: " + message),
            message => Console.WriteLine("Function 2: " + message),
            message => Console.WriteLine("Function 3: " + message.ToUpper())
        };
        
        // 调用数组中的函数
        foreach (var func in functions)
        {
            func("Hello from C#");
        }
    }
}

2. 使用 Action/Func 泛型委托

代码语言:txt
复制
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 使用 Action 委托(无返回值)
        List<Action<string>> actions = new List<Action<string>>
        {
            s => Console.WriteLine(s),
            s => Console.WriteLine(s.Length),
            s => Console.WriteLine(s.ToUpper())
        };
        
        actions.ForEach(action => action("Test"));
        
        // 使用 Func 委托(有返回值)
        List<Func<int, int, int>> mathFunctions = new List<Func<int, int, int>>
        {
            (a, b) => a + b,
            (a, b) => a * b,
            (a, b) => (int)Math.Pow(a, b)
        };
        
        foreach (var func in mathFunctions)
        {
            Console.WriteLine(func(2, 3));
        }
    }
}

3. 处理带上下文的函数

如果需要类似 JavaScript 的 this 绑定,可以使用类实例方法:

代码语言:txt
复制
using System;
using System.Collections.Generic;

class Processor
{
    private string prefix;
    
    public Processor(string prefix)
    {
        this.prefix = prefix;
    }
    
    public void Process(string message)
    {
        Console.WriteLine(prefix + ": " + message);
    }
}

class Program
{
    static void Main()
    {
        var processors = new List<Processor>
        {
            new Processor("INFO"),
            new Processor("WARNING"),
            new Processor("ERROR")
        };
        
        var actions = new List<Action<string>>();
        foreach (var p in processors)
        {
            actions.Add(p.Process);
        }
        
        actions.ForEach(action => action("Something happened"));
    }
}

常见问题及解决方案

问题1:如何处理不同签名的函数?

解决方案:使用接口或基类定义统一接口,然后实现多态。

代码语言:txt
复制
interface IOperation
{
    void Execute(string input);
}

class UpperCaseOperation : IOperation
{
    public void Execute(string input) => Console.WriteLine(input.ToUpper());
}

class LengthOperation : IOperation
{
    public void Execute(string input) => Console.WriteLine(input.Length);
}

// 使用
List<IOperation> operations = new List<IOperation>
{
    new UpperCaseOperation(),
    new LengthOperation()
};

operations.ForEach(op => op.Execute("test"));

问题2:如何实现异步函数数组?

解决方案:使用 Func<Task>Func<T, Task> 委托。

代码语言:txt
复制
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        List<Func<string, Task>> asyncFunctions = new List<Func<string, Task>>
        {
            async s => {
                await Task.Delay(1000);
                Console.WriteLine("Async 1: " + s);
            },
            async s => {
                await Task.Delay(500);
                Console.WriteLine("Async 2: " + s.ToUpper());
            }
        };
        
        foreach (var func in asyncFunctions)
        {
            await func("hello");
        }
    }
}

应用场景

  1. 插件系统:动态加载和执行不同功能模块
  2. 事件处理:管理多个事件处理器
  3. 中间件管道:如ASP.NET Core的中间件
  4. 策略模式:不同算法或策略的集合
  5. 工作流系统:按顺序执行一系列操作

优势对比

| 特性 | JavaScript | C# | |------|-----------|----| | 灵活性 | 高(动态类型) | 中(需要类型定义) | | 类型安全 | 无 | 强类型检查 | | 性能 | 较低(解释执行) | 高(JIT编译) | | 调试便利性 | 一般 | 优秀 | | 上下文绑定 | 自动(this) | 需要显式处理 |

通过以上方法,可以在C#中实现JavaScript函数数组的类似功能,同时获得类型安全和性能优势。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的文章

领券