c# - 具有 x 个附加对象的类
问题描述
假设我有一个带有构造函数的名为 Person 的类
public class Person
{
public string Name { get; set;}
public string Height { get; set; }
public string WhatEverElse { get; set; }
public string Person(string Name, string Height, string WhatEverElse)
{
this.Name = Name;
.......
}
}
现在假设我还想包括一个人可能拥有的所有宠物。
List<Person> persons = new List<Person>();
persons.Add(new Person("Larry", "5'9", "Whatever"));
foreach(Datarow row in OwnedPets)
{
//push the pet info to the person here
}
有没有办法可以将 x 数量的宠物和宠物信息添加到 Person 对象?这样我就可以带回拉里和他的所有 2 只宠物或杰里和他的所有 6 只宠物?或者我可以结合两个类并返回一个列表吗?
解决方案
清单怎么样?
public class Person
{
public string Name { get; set;}
public string Height { get; set; }
public string WhatEverElse { get; set; }
public List<Pet> Pets { get; set; }
public string Person(string Name, string Height, string WhatEverElse)
{
Pets = new List<Pet>();
}
}
public class Pet
{
public string Name { get; set; }
}
然后,您可以通过分配新宠物来添加任意数量的宠物
// For your own sake keep a clear naming convention - just my two bucks
List<Person> persons = new List<Person>();
Person person = new Person("Larry", "5'9", "Whatever");
persons.Add(person);
foreach(Datarow row in OwnedPets)
{
Pet newPet = new Pet();
person.Pets.Add(newPet);
}
推荐阅读
- javascript - 如何在反应传单中制作椭圆?
- javascript - 在js“window.location”中将Url添加为变量不起作用
- php - 如何更换
我想清理我的 php 文件。我真的很喜欢刀片模板如何使用花括号来显示 php 变量
{{ $user }}
https://laravel.com/docs/5.8/blade#- java - 继承中的重载
- amazon-s3 - 使用自定义名称将数据框保存到 S3
- asp.net-core - Asp.Net Core Mvc 中的全局模型状态验证
- javascript - JavaScript:如何处理所有后续的元素对?
- javascript - Angular:多选下拉ID
- google-cloud-platform - gcloud 崩溃(TokenRevokeError):invalid_request
- bash - ubuntu/macos 中的单行打印文件校验和