Interesting “params of ref” feature, any workarounds?

前端 未结 5 1223
轮回少年
轮回少年 2020-11-27 19:38

I wonder if there\'s any way something like this would be possible for value types...

public static class ExtensionMethods {
    public static void SetTo(thi         


        
5条回答
  •  情话喂你
    2020-11-27 20:04

    There isn't really a way. You could do something like this:

    public static void Main(string[] args)
    {
        BooleanWrapper a = true, b = true, c = true, d = true, e = new BooleanWrapper();
        b.SetTo(a, c, d, e);
    }
    
    public static void SetTo(this BooleanWrapper sourceWrapper, params BooleanWrapper[] wrappers)
    {
        foreach (var w in wrappers)
            w.Value = sourceWrapper.Value;
    }
    
    public class BooleanWrapper
    {
        public BooleanWrapper() { }
    
        public BooleanWrapper(Boolean value)
        {
            Value = value;
        }
    
        public Boolean Value { get; set; }
    
        public static implicit operator BooleanWrapper(Boolean value)
        {
            return new BooleanWrapper(value);
        }
    }
    

    But then again how is that any better than just doing this:

    public static void Main(string[] args)
    {
        Boolean[] bools = new Boolean[5];
        bools.SetTo(bools[1]); // Note I changed the order of arguments. I think this makes more sense.
    }
    
    public static void SetTo(this Boolean[] bools, Boolean value)
    {
        for(int i = 0; i < bools.Length; i++)
            bools[i] = value;
    }
    

    After all, an array is a sequence of variables. If you need something that behaves like a sequence of variables, use an array.

提交回复
热议问题