Change value inside an (void) extension method

前端 未结 6 1031
心在旅途
心在旅途 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:11

    According to this answer: https://stackoverflow.com/a/1259307/1945651, there is not a way to do this in C#. Primitive types like int are immutable, and cannot be modified without an out or ref modifier, but the syntax won't allow out or ref here.

    I think your best case is to have the extension method return the modified value instead of trying to modify the original.

    Apparently this is possible in VB.NET and if you absolutely needed it, you could define your extension method in a VB.NET assembly, but it is probably not a very good practice in the first place.

提交回复
热议问题