积极答复者
如何把 ref 保存起来?

问题
-
class Change // A:正确的写法 { public void Update(ref int i, int newValue) { i = newValue; } }
class Change // B:我想达到的目标 { public void SetValueRef(ref int i); public void Update(int newValue); }
如上面的代码,我们知道A可以实现修改一个变量的值,但是 ref i 的传入和值的修改必定同时发生。我想要,先把 ref i 传入,未来需要的时候再修改 i 的值,这该如何实现?或者有什么变通的方法?
答案
-
因为ref只能在函数中用,不能用于事件啥的,要不用类封装一下,借助类的特性改变。譬如:
public class A { public int I { get; set; } public A(int i) { I = i; } /// <summary> /// 更新数据的方法 /// </summary> public void Update(int newInt) { I = newInt; } } public class MainTest { static void Main(string[] args) { A a = new A(0); Console.WriteLine("源数据:"+a.I); a.Update(2); Console.WriteLine("新数据:"+a.I); } }
If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer
Help by clicking:
Click here to donate your rice to the poor
Click to Donate
Click to feed Dogs & Cats
Found any spamming-senders? Please report at: Spam Report- 已标记为答案 skyoxZ 2013年8月18日 14:04
全部回复
-
如果你想调用Update方法(手动调用)才更改i,那么可以考虑设置一个布尔值:
class Change // B:我想达到的目标 { public void Update(int newValue,ref int i,bool flag) { if(flag) { i = newValue; } } }
If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer
Help by clicking:
Click here to donate your rice to the poor
Click to Donate
Click to feed Dogs & Cats
Found any spamming-senders? Please report at: Spam Report -
因为ref只能在函数中用,不能用于事件啥的,要不用类封装一下,借助类的特性改变。譬如:
public class A { public int I { get; set; } public A(int i) { I = i; } /// <summary> /// 更新数据的方法 /// </summary> public void Update(int newInt) { I = newInt; } } public class MainTest { static void Main(string[] args) { A a = new A(0); Console.WriteLine("源数据:"+a.I); a.Update(2); Console.WriteLine("新数据:"+a.I); } }
If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer
Help by clicking:
Click here to donate your rice to the poor
Click to Donate
Click to feed Dogs & Cats
Found any spamming-senders? Please report at: Spam Report- 已标记为答案 skyoxZ 2013年8月18日 14:04