C#扩展方法返回值未设置变量 [英] C# Extension Method Return Value Not Setting Variable

查看:84
本文介绍了C#扩展方法返回值未设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此扩展方法未设置应用于它的值?

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;
}

这是电话(selectedIndex = 13):

This is the call ( selectedIndex = 13 ):

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

在控制台上写入"test:FF".

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'));

在控制台上写入"test:ED".我不需要重新分配变量吗?我写了许多其他扩展.

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

推荐答案

我想念什么吗?

Am I missing something?

是-您不是在第一个代码段中使用方法的返回值.您所需要的就是设置返回值,就像您在工作案例中所做的一样(您的第二个代码段).更改 parameter 的值没有区别,因为它是一个按值参数.在这里,您使用扩展方法的事实是无关紧要的.

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);

毕竟,这就是编译器将您的代码转换为的内容.如果您忽略了它是扩展方法的事实(您应该这样做,因为它与此处无关),您会期望它更改test的值吗?为此,您需要通过引用(使用ref)传递它-但是扩展方法的第一个参数不允许具有ref修饰符.

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.

这篇关于C#扩展方法返回值未设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆