Change value inside an (void) extension method

前端 未结 6 1114
心在旅途
心在旅途 2021-02-12 23:28

So I have this mock extension method which change a value to another value:

public static void ChangeValue(this int value, int valueToChange)
{
    value = value         


        
6条回答
  •  不要未来只要你来
    2021-02-13 00:17

    I know it's too late, but just for the record, I recently really wanted to do this, I mean...

    someVariable.ChangeValue(10);
    

    ...apparently looks way neat than the following (which is also perfectly fine)

    ChangeValue(ref someVariable, 10);
    

    And I managed to achieve something similar by doing:

    public class MyClass
    {
        public int ID { get; set; }
        public int Name { get; set; }
    }
    
    public static void UpdateStuff(this MyClass target, int id, string name)
    {
        target.ID = id;
        target.Name = name;
    }
    
    static void Main(string[] args)
    {
        var someObj = new MyClass();    
    
        someObj.UpdateStuff(301, "RandomUser002");
    }
    

    Note that if the argument passed is of reference type, it needs to be instantiated first (but not inside the extension method). Otherwise, Leri's solution should work.

提交回复
热议问题