简体   繁体   中英

What is the equivalent javascript closure in c#?

Consider this simple .js code:

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. What is the equivalent closure in c#?

I have made this:

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

You could use a mix of ValueTuples and lambda expressions .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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