我有一个扩展方法的代码,它看上去像行
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);
}
}这是我的扩展类,但我需要的是
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
}我找不到办法来解决这个问题,请推荐一个解决方案。
发布于 2019-07-30 11:04:04
首先,我强烈建议你不要这样做。这很违反直觉。
但在C# 7.2中,使用ref扩展方法是可能的--仅对于值类型。只需将第一个参数更改为具有ref修饰符,并将其赋值:
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)调用是隐式的:
Int32Extensions.Add(ref i, 2);如果你试图对不是变量的东西调用它,它就会失败。
但对于许多C#开发人员来说,这将是非常令人惊讶的行为,因为ref是隐式的。它也不适用于引用类型。
https://stackoverflow.com/questions/57270131
复制相似问题