【问题标题】:How to pass a "path" to an object member in C#?如何将“路径”传递给 C# 中的对象成员?
【发布时间】:2010-09-13 17:44:18
【问题描述】:

说我有

public class family
{
   public person father;
   public person mother;
   public person[] child;
}

public class person
{
   public string name;
   public int age;
}

我想要做的是向家庭添加一个功能,让我可以指定我希望将新人保存到的位置。

如果有 C,我会传递一个指向 person 的指针,这样我就可以将它指向一个新人,但我对 C# 有点陌生,不知道在这里做什么。所以我希望它看起来像这样:

public void SavePerson(int newAge, string newName, ??? location)
{
   person addMe = new person();
   addMe.age = newAge;
   addMe.name = newName;
   location = addMe;
}

我不想更改以前的位置内容。如果它曾经指向弗兰克,我想让弗兰克保持原来的样子,我只想让它现在指向约翰(因为其他东西可能仍然指向弗兰克)

我需要这个的原因是因为我有一个比这更复杂的接口和类。但是有一个类我需要创建并保存很多(它出现在一个大型 NHibernate 创建的对象中),为了简单起见,我想将它整合到一个函数中。

【问题讨论】:

标签: c# pointers


【解决方案1】:

惯用的 C# 做事方式是简单地返回新对象:

public Person CreatePerson(int age, string name)
{
    Person person = new Person();
    person.Age = age;
    person.Name = name;
    return person;
}

用法:

family.Children[0] = CreatePerson(11, "Frank");
family.Children[1] = CreatePerson(15, "John");

或者,您可以将Person[] 和索引传递给方法:

public void SavePerson(int age, string name, Person[] persons, int index)
{
    persons[index] = new Person();
    persons[index].Age = age;
    persons[index].Name = name;
}

用法:

SavePerson(11, "Frank", family.Children, 0);
SavePerson(15, "John",  family.Children, 1);

但我不确定你为什么要将这个责任委托给你的工厂方法。


如果您真的想通过引用来操作变量内容,可以使用 refout 关键字:

public void SavePerson(int age, string name, out Person person)
{
    person = new Person();
    person.Age = age;
    person.Name = name;
}

用法:

SavePerson(11, "Frank", out family.Children[0]);
SavePerson(15, "John",  out family.Children[1]);

见:Parameter passing in C#

见:When is using the C# ref keyword ever a good idea?


但是为什么不简单地使用对象和集合初始化器呢?

Person mom = new Person { Age = 41, Name = "Martha" };
Person dad = new Person { Age = 43, Name = "Dan"    };

Family family = new Family(mom, dad)
{
    new Person { Age = 11, Name = "Frank" },
    new Person { Age = 15, Name = "John"  },
};

见:Object and Collection Initializers

【讨论】:

  • Ref 和 Out 关键字是我一直在寻找的,但对象初始化器可能是我在这里使用的。谢谢!
猜你喜欢
  • 2013-12-26
  • 1970-01-01
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 2019-01-26
  • 2023-03-28
  • 1970-01-01
相关资源
最近更新 更多