//something is wrong with Parents setter property idk what :C,
//i'm getting an exception when third ctor executes...
class Person {
public string Name { get;set; }
public DateTime DateOfBirth { get; private set; }
public IEnumerable<Person> Parents { get { return (Person[])Parents; }
private set { Parents = value; } } // I'm getting StackOverFlow here BUT WHY ?
public Person(string Name,DateTime DateOfBirth,Person[] parents=null)
{
this.Name = Name;this.DateOfBirth = DateOfBirth;Parents = parents;
}
}
// Main class
class Program
{
static void Main(string[] args)
{
//Creating 3 objects and get exception on third
Person prs = new Person("Emily", DateTime.Now, null);
Person prss = new Person("mark", DateTime.Now);
Person psrs = new Person("maras", DateTime.Now, new[] { prs, prss });
if (psrs.Parents != null)
{
foreach (var parent in psrs.Parents)
Console.WriteLine();
}
else Console.WriteLine("No parents");
}
}
//问题此外:我的班级实现是否符合OOP的所有原则? //好吧也许是因为在构造函数和属性中我做了完全相同的事情但是如果我在ctor中删除Parent = parent我怎么能通过构造函数初始化我的Parents属性?如果我删除我的设置propery我也无法初始化Parents属性。求救!
答案 0 :(得分:1)
您的Parents
媒体资源已设置在setter
内。您需要有一个合适的支持领域。
private IEnumerable<Person> _parents
public IEnumerable<Person> Parents
{
get { return (Person[])_parents; }
private set
{
_parents = value;
}
}
修改强>: 您也可以使用自动属性,因为我认为不需要支持字段。
public IEnumerable<Person> Parents { get; private set; }
答案 1 :(得分:1)
正如@crashmstr所说,Parents
正在引用自己。这里有一点解释:
public IEnumerable<Person> Parents
{
get
{
return (Person[])Parents;
}
private set
{
Parents = value;
}
}
使用C#时,这样的属性基本上编译成以下代码:
public IEnumerable<Person> Parents_get()
{
return (Person[])Parents.get();
}
public void Parents_set(IEnumerable<Person> value)
{
Parents_set(value);
}
这使得为什么它自我引用更加清晰。
您只需将您的媒体资源定义为:
即可public IEnumerable<Person> Parents { get; set; }