问题描述
|
class Program
{
static void Main()
{
int i = 0;
whatever x = new whatever(i);
Console.WriteLine(x);
i = 1;
Console.WriteLine(x);
Console.ReadKey();
}
class whatever
{
public whatever(object variable)
{
this.variable = () => variable.ToString();
}
private Func<string> variable;
public string data;
public override string ToString()
{
data = variable();
return data;
}
}
输出:
0
0
我想做的就是获取更新的i \的值。
解决方法
也许问题是委托绑定到装箱的整数数据。这就是为什么您更改int并委托评估为旧装箱数据的原因。
尝试使用需要int的构造函数。
但是,是的,确实是通过值粘贴了整数,因此这是行不通的。
将委托传递给ctor。
class Program
{
static void Main()
{
int i = 0;
whatever x = new whatever(() => i.ToString());
Console.WriteLine(x);
i = 1;
Console.WriteLine(x);
Console.ReadKey();
}
class whatever
{
public whatever(Func<string> someFunc)
{
this.variable = someFunc;
}
private Func<string> variable;
public string data;
public override string ToString()
{
data = variable();
return data;
}
}
}
输出:
0
1个
或如其他指示所示:
class Program
{
static void Main()
{
var myRefType = new MyRefType();
myRefType.MyInt = 0;
var x = new whatever(myRefType);
Console.WriteLine(x);
myRefType.MyInt = 1;
Console.WriteLine(x);
Console.ReadKey();
}
class whatever
{
public whatever(MyRefType myRefType)
{
this.variable = () => myRefType.MyInt.ToString();
}
private Func<string> variable;
public override string ToString()
{
return variable();
}
}
class MyRefType
{
public int MyInt { get; set; }
}
}
输出:
0
1个
, 如果要捕获局部变量,则将lambda放在错误的位置。 Lambda必须移至要捕获的外部变量可以关闭的位置。
class Program
{
static void Main()
{
int i = 0;
var x = new Whatever<int>(()=>i);
Console.WriteLine(x);
i = 1;
Console.WriteLine(x);
Console.ReadKey();
}
}
class Whatever<T>
{
private Func<T> variable;
public Whatever(Func<T> func)
{
this.variable= func;
}
public override string ToString()
{
return this.variable().ToString();
}
}
那有意义吗?参见,lambda必须位于声明“ i”的位置,以便“ i”是lambda的外部变量,因此lambda会看到对其的更改。
, i是一个整数(值类型),它由值传递-值的副本传递给any构造函数。当您在Main方法上更改其值时,它不会更改已传递给该类的内容。因此,您无法在whatever
上获得更新的值。
如果您有一个对象,该对象持有一个整数值的字段,然后将该对象传递给whatever
,则对该字段的更改将反映在类上。
, 整数是值类型,而不是引用类型。
, int
是值类型,表示每次使用时都会复制其值,而不是引用。最好的方法是在int周围创建引用类型:
class IntRef
{
public int Val;
}
您将需要始终使用IntRef.Val
,而将IntVal
本身传递过来将保留参考。