C# Extension Method Return Value Not Setting Variable

会有一股神秘感。 提交于 2019-12-24 03:16:31

问题


Why doesn't this extension method set the value it's applied to?

public static byte ExtSetBits(this byte original, byte value, byte bitSize)
{
    unchecked { original &= (byte)~bitSize; }
    original |= (byte)(value & bitSize);
    return original;
}

This is the call ( selectedIndex = 13 ):

byte test = 0xFF;
test.ExtSetBits(selectedIndex, 0x1F);
Console.WriteLine("test:" + test.ToString("X").PadLeft(2,'0'));

Writes "test: FF" to the console.

If I do this it works:

byte test = 0xFF;
test = test.ExtSetBits(selectedIndex, 0x1F);
Console.WriteLine("test:" + test.ToString("X").PadLeft(2,'0'));

Writes "test: ED" to the console. I shouldn't have to reassign the variable right? I've written many other extensions.


回答1:


Am I missing something?

Yes - you're not using the return value of the method in your first snippet. All you need is to set the return value, just as you're doing in the working case (your second code snippet). Changing the value of the parameter makes no difference, because it's a by-value parameter. The fact that you're using an extension method is irrelevant here.

Imagine your code was actually just:

ExtensionClass.ExtSetBits(test, selectedIndex, 0x1F);

After all, that's what the compiler is converting your code to. If you ignore the fact that it's an extension method (which you should, as it's irrelevant here) would you expect that to change the value of test? To do that, you'd need to pass it by reference (with ref) - but an extension method's first parameter isn't allowed to have the ref modifier.

You might want to read my article about parameter passing for a bit more background, along with my article about value types and reference types.




回答2:


byte is a value type. test and original are both distinct values, modifying one does not modify the other.




回答3:


You are not modifying the value of the test in your function. The parameter is a copy of your variable, you are changing it's value and then returning it. If you want to manipulate the variable then you should use ref modifier but the first parameter of extension method can't be declared as ref.



来源:https://stackoverflow.com/questions/25289093/c-sharp-extension-method-return-value-not-setting-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!