c# multi assignment

后端 未结 7 1784
温柔的废话
温柔的废话 2020-12-16 13:54
int a, b, n;
...
(a, b) = (2, 3);
// \'a\' is now 2 and \'b\' is now 3

This sort of thing would be really helpfull in C#. In this example \'a\' and

相关标签:
7条回答
  • 2020-12-16 14:23

    use case:

    it'd be really nice for working with IObservables, since those have only one type parameter. you basically want to subscribe with arbitrary delegates, but you're forced to use Action, so that means if you want multiple parameters, you have to either use tuples, or create custom classes for packing and unpacking parameters.

    example from a game:

    public IObservable<Tuple<GameObject, DamageInfo>> Damaged ...
    
    void RegisterHitEffects() {
        (from damaged in Damaged
         where damaged.Item2.amount > threshold
         select damaged.Item1)
        .Subscribe(DoParticleEffect)
        .AddToDisposables();
    }
    

    becomes:

    void RegisterHitEffects() {
        (from (gameObject, damage) in Damaged
         where damage.amount > threshold
         select gameObject)
        .Subscribe(DoParticleEffect)
        .AddToDisposables();
    }
    

    which i think is cleaner.

    also, presumably IAsyncResult will have similar issues when you want to pass several values. sometimes it's cumbersome to create classes just to shuffle a bit of data around, but using tuples as they are now reduces code clarity. if they're used in the same function, anonymous types fit the bill nicely, but they don't work if you need to pass data between functions.

    also, it'd be nice if the sugar worked for generic parameters, too. so:

    IEnumerator<(int, int)>
    

    would desugar to

    IEnumerator<Tuple<int,int>>
    
    0 讨论(0)
提交回复
热议问题