在 JavaScript 中,函数是一等公民,可以像普通变量一样存储在数组中。这种模式常用于回调函数集合、插件系统或事件处理器管理。C# 作为静态类型语言,处理方式有所不同,但可以通过委托(delegate)实现类似功能。
this
绑定,C# 需要显式处理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#");
}
}
}
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));
}
}
}
如果需要类似 JavaScript 的 this
绑定,可以使用类实例方法:
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"));
}
}
解决方案:使用接口或基类定义统一接口,然后实现多态。
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"));
解决方案:使用 Func<Task>
或 Func<T, Task>
委托。
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");
}
}
}
| 特性 | JavaScript | C# | |------|-----------|----| | 灵活性 | 高(动态类型) | 中(需要类型定义) | | 类型安全 | 无 | 强类型检查 | | 性能 | 较低(解释执行) | 高(JIT编译) | | 调试便利性 | 一般 | 优秀 | | 上下文绑定 | 自动(this) | 需要显式处理 |
通过以上方法,可以在C#中实现JavaScript函数数组的类似功能,同时获得类型安全和性能优势。
没有搜到相关的文章