我正在尝试将引用类型对象传递给方法并从那里更改它。当我更改它时,我没有对传递给方法的变量进行更改。
I am trying to pass reference type object into a method and changing it from there. When I change it I don't have that change on the variable which is passed to method.
以下是示例:
public interface IPerson { string Name { get; } } public class Teacher : IPerson { public string Name { get; set; } public string LastName { get; set; } } //...... public void CreateTeacher(IPerson teacher) { teacher = new Teacher() { Name = "Teacher name", LastName = "Teacher's last name"}; } //..... //I am trying this, but after I call CreateTeacher() variable teacher is null IPerson teacher=null; CreateTeacher(teacher); string n = teacher.Name;运行 CreateTeacher()变量老师是还是空的?有人可以解释为什么吗我知道我可以在我的 CreateTeacher()方法上返回 IPerson 或使用 out ,但我不能使用它们。
After running CreateTeacher() variable teacher is still null? Can anyone explain why? I know I could return IPerson on my CreateTeacher() method or use out, but I can't use them.
IPerson 界面位于不同的dll和教师 class是一个不同的dll。方法 CreateTeacher 与class相同。
The IPerson interface is in a different dll and Teacher class is in a different dll. The method CreateTeacher is the same dll where class is.
更新:
这是我尝试过的其他内容:
Here is something else I tried:
IPerson teacher=new Teacher(); CreateTeacher(teacher); string n = teacher.Name;//I have the changes here now //...... public void CreateTeacher(IPerson teacher) { ((Teacher)teacher).Name = "My Name"; }第一个例子和第二个例子有什么区别?是因为传递的值是 null ?
What is the difference between 1st example and 2nd? Is it because of the passed value was null?
感谢您的帮助!
推荐答案除了RedPolygon的答案之外......我觉得这可能会让事情变得清晰。
In addition to RedPolygon's answer.. I feel like this might clear things up.
As解释,您正在更改引用的值..而不是引用指向的对象。
As explained, you're changing the value of the reference.. not the object pointed to by the reference.
将代码更改为:
public interface IPerson { string Name { get; set; } } public void CreateTeacher(IPerson teacher) { teacher.Name = "Teacher name"; } IPerson teacher = new Teacher(); CreateTeacher(teacher);..这将有效。为什么?有几个原因。
..that will work. Why? A couple of reasons.
令人困惑......是的,但你明白了你可以玩这样的例子。
It's confusing.. yes, but you understand it when you have a play around with examples like this.
编辑:
我不得不点燃油漆并放我展示了令人敬畏的MSPaint技能:
I had to fire up paint and put my awesome MSPaint skills on display:
这是你的第一个片段流程:
This is your first snippet flow:
这是我的代码段(和你的第二个)一)):
This is my snippet (and your second one):
更多推荐
传递引用类型对象并更改值
发布评论