This question already has answers here:
Overloading getter and setter causes a stack overflow in C# [duplicate]
(4个答案)
1年前关闭。
这是我的代码。我无法弄清楚为什么这段代码给出“由于StackOverFlowException而终止了进程”。
这是输出。
有人可以解释原因吗?为什么它在第一部分起作用而不在另一部分起作用?
具体来说
这是您想要的吗?
(4个答案)
1年前关闭。
这是我的代码。我无法弄清楚为什么这段代码给出“由于StackOverFlowException而终止了进程”。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SadiSDAL4
{
class Program
{
static void Main(string[] args)
{
PrivateVehical privateV = new PrivateVehical("001");
PrivateVehical pVehical = (PrivateVehical)privateV.Clone();
Console.WriteLine("Cloned : {0}", privateV.name);
Console.WriteLine("Cloned : {0}", pVehical.name);
privateV.name = "Sadia's Car";
Console.WriteLine("Cloned : {0}", privateV.name);
Console.WriteLine("Cloned : {0}", pVehical.name);
pVehical.name = "Waheed's Car";
Console.WriteLine("Cloned : {0}", privateV.name);
Console.WriteLine("Cloned : {0}", pVehical.name);
Console.WriteLine(privateV.GetHashCode().ToString());
Console.WriteLine(pVehical.GetHashCode().ToString());
PublicVehical publicV = new PublicVehical("002");
Console.WriteLine(publicV.id);
PublicVehical pubVehi = (PublicVehical)publicV.Clone();
Console.WriteLine("Cloned : {0}", pubVehi.id);
}
}
abstract class Vehical
{
private string vehicalId = "01";
public string name = "Car_1";
public Vehical(string id)
{
this.vehicalId = id;
}
public string id
{
get { return id; }
set { this.vehicalId = id; }
}
public abstract Vehical Clone();
}
class PrivateVehical : Vehical
{
public PrivateVehical(string id)
: base(id)
{
}
public override Vehical Clone()
{
return (Vehical)this.MemberwiseClone();
}
}
class PublicVehical : Vehical
{
public PublicVehical(string id)
: base(id)
{
}
public override Vehical Clone()
{
return (Vehical)this.MemberwiseClone();
}
}
}
这是输出。
有人可以解释原因吗?为什么它在第一部分起作用而不在另一部分起作用?
最佳答案
看一下这段代码:
public string id
{
get { return id; }
set { this.vehicalId = id; }
}
具体来说
get { return id; }
。您正在将属性返回给自身,从而导致SO错误。这是您想要的吗?
public string id
{
get { return this.vehicalId; }
set { this.vehicalId = value; }
}
09-25 20:56