简体   繁体   English

c#中等效的javascript闭包是什么?

[英]What is the equivalent javascript closure in c#?

Consider this simple .js code: 考虑一下这个简单的.js代码:

const createCounter = () => {
    let value = 0;
    return {
        increment: () => { value += 1 },
        decrement: () => { value -= 1 },
        logValue: () => { console.log(value); }
    }
}

// Usage //用法

const { increment, decrement, logValue } = createCounter();

I'm pretty sure c# support first class function, note that I don't want to use classes to remake the code above. 我很确定c#支持第一类函数,请注意我不想使用类重新编写上面的代码。 What is the equivalent closure in c#? c#中的等价闭包是什么?

I have made this: 我做了这个:

public Func<WhatType?> CreateCounter = () => {
    var value = 0;
    return what?
}

You could use a mix of ValueTuples and lambda expressions . 您可以使用ValueTupleslambda表达式的混合。

private static (Action increment, Action decrement, Action logValue) CreateCounter()
{
    var value = 0;

    return
        (
            () => value += 1,
            () => value -= 1,
            () => Console.WriteLine(value)
        );
}

Usage 用法

var (increment, decrement, logValue) = CreateCounter();
increment();
increment();
decrement();
logValue();

Check out the following code using Dictionary to Map enumerated data types with an Action Delegate 使用Dictionary来映射以下代码,使用Action Delegate映射enumerated data types

void Main()
{
    OperationActionDictionary[Operation.Increment](); // Execute Increment
    OperationActionDictionary[Operation.Increment](); // Execute Increment
    OperationActionDictionary[Operation.Decrement](); // Execute Decrement
    OperationActionDictionary[Operation.LogValue]();  // Execute LogValue
}

public enum Operation
{
    Increment,
    Decrement,
    LogValue
}

public static int Value = 0;

public Dictionary<Operation,Action> OperationActionDictionary = new Dictionary<Operation, Action>
{
    [Operation.Increment] = () => Value += 1,
    [Operation.Decrement] = () => Value -= 1,
    [Operation.LogValue] = () => Console.WriteLine($"Value :: {Value}")
};

Only catch here or in any other code for modifying a shared Value object would be in case it is Multi thread access, then you need to take care of thread safety in this case using Interlocked.Increment or Interlocked.Decrement 只有在这里或者用于修改共享Value对象的任何其他代码时,如果它是多线程访问,那么在这种情况下你需要使用Interlocked.IncrementInterlocked.Decrement来处理线程安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM