首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c#中的扩展方法--如何将值赋值给父变量,即"this“变量

c#中的扩展方法--如何将值赋值给父变量,即"this“变量
EN

Stack Overflow用户
提问于 2019-07-30 11:01:28
回答 1查看 647关注 0票数 1

我有一个扩展方法的代码,它看上去像行

代码语言:javascript
复制
parent class
{
   int i = 9; // the value was i was 9;
   i = i.Add(2); // here 9 + 2
   Console.WriteLine(i); // it is printing 11
}

extension class
{
   public static int Add(this int firstInteger, int secondInteger)
   {
      return (firstInteger + secondInteger);
   }
}

这是我的扩展类,但我需要的是

代码语言:javascript
复制
parent class
{
   int i = 9;              // the value was i was 9;
   i.Add(2);              // here 9 + 2
   Console.WriteLine(i); // it has to print 11
}

我找不到办法来解决这个问题,请推荐一个解决方案。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-30 11:04:04

首先,我强烈建议你不要这样做。这很违反直觉。

但在C# 7.2中,使用ref扩展方法是可能的--仅对于值类型。只需将第一个参数更改为具有ref修饰符,并将其赋值:

代码语言:javascript
复制
using System;

public static class Int32Extensions
{
    public static void Add(ref this int x, int y)
    {
        x = x + y;
    }

}

class Test
{
    static void Main()
    {
        int i = 9;
        i.Add(2);
        Console.WriteLine(i); // 11
    }
}

i.Add(2)调用是隐式的:

代码语言:javascript
复制
Int32Extensions.Add(ref i, 2);

如果你试图对不是变量的东西调用它,它就会失败。

但对于许多C#开发人员来说,这将是非常令人惊讶的行为,因为ref是隐式的。它也不适用于引用类型。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57270131

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档