简体   繁体   English

C#用扩展方法改变一个值

[英]C# changing a value with extension method

If I have the following extension methods: 如果我有以下扩展方法:

internal static class Extensions
{
    public static void Increase(this uint value)
    {
        value += 1;
    }

    public static void Decrease(this uint value)
    {
        if (value > 0) value -= 1;
    }
}

Why does this not result in a changing i to 1? 为什么这不会导致i变为1?

uint i = 0;
i.Increase();

The parameter is being passed by value, that's all. 参数是通过值传递的,这就是全部。 There's nothing special about extension methods on this front. 这方面的扩展方法没什么特别之处。 It's equivalent to: 它相当于:

Extensions.Increase(i);

You'd need the method to have the first parameter passed by reference (with ref ) for that to have any effect... and that's prohibited for extension methods anyway. 您需要使用该方法通过引用(使用ref )传递第一个参数,以使其具有任何效果......并且无论如何都禁止使用扩展方法。

So while you could write a method allowing you to call it as: 因此,虽然您可以编写一个方法,允许您将其称为:

Extensions.Increase(ref i);

you won't be able to make that an extension method. 你将无法成为一种扩展方法。

An alternative is to make the method return a value, at which point you could have: 另一种方法是使方法返回一个值,此时您可以:

i = i.Increase();

If you're not entirely clear on pass-by-reference vs pass-by-value semantics, you might want to read my article on the topic . 如果您不完全清楚传递引用和传值值语义,那么您可能希望阅读有关该主题的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM