Last active
December 14, 2015 15:08
-
-
Save yicone/5105180 to your computer and use it in GitHub Desktop.
从集合里取出来的,还是原来的引用吗
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
// 初始化一个context | |
var cxt = new Context(); | |
cxt.StepModel1 = new StepModel1{ Name = "foo1" }; | |
cxt.StepModel2 = new StepModel2{ Name = "foo2" }; | |
// 从context一个方法的内部的集合中取出一个model | |
var model1 = cxt.GetStepModel(1); | |
// 试着更新它 | |
var newModel = new StepModel1{ Name = "foo3" }; | |
model1 = newModel; | |
// ! 失败鸟 | |
Console.WriteLine(cxt.StepModel1.Name); | |
} | |
// Define other methods and classes here | |
public class Context | |
{ | |
public StepModel1 StepModel1 {get;set;} | |
public StepModel2 StepModel2 {get;set;} | |
public IStepModel GetStepModel(int no) | |
{ | |
List<IStepModel> list = new List<IStepModel>{ this.StepModel1, this.StepModel2 }; | |
return list.Single(m => m.No == no); | |
} | |
} | |
public interface IStepModel | |
{ | |
int No {get;} | |
} | |
public class StepModel1 : IStepModel{ | |
public int No { get {return 1;}} | |
public string Name {get;set;} | |
} | |
public class StepModel2 : IStepModel{ | |
public int No { get {return 2;}} | |
public string Name {get;set;} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
引用本身是按值copy的(by value)
var cxt = new Context();
// 创建了实例A,并且把对应的引用copy给了cxt的StepModel1字段
cxt.StepModel1 = new StepModel1{ Name = "foo1" };
cxt.StepModel2 = new StepModel2{ Name = "foo2" };
// 创建了实例B,并且把对应的引用copy给了newModel变量
var newModel = new StepModel1{ Name = "foo3" };
// GetStepModel是实例A的引用,这个应该没问题吧
// 然后将此引用copy到了model1变量
var model1 = cxt.GetStepModel(1);
// 修改了model1变量(model1不再是实例A的引用,而是实例B的引用)
model1 = newModel;
// 好吧,重新去StepModel1的那个引用,不过谁也没改过这个引用,所以它依然是一个指向实例A的引用
Console.WriteLine(cxt.StepModel1.Name);