سؤال

apologize me if this is noob question.
I have the following abstract base class:

public abstract class MockDataBase
{
  public virtual string ExternalId { get; set; }

And i have the derived class:

public class UnitMockDataBase: MockDataBase
{
 public override string ExternalId { set { ExternalId = value; } }

this throws stack overflow.
If i want the base class to have the property:

public virtual string ExternalId { get; private/protected set; }  

And dervied classes to override its setter, how do i implement it ? the base class CANNOT have external id, only some of the derived class use it and need to over ride.

thanks

هل كانت مفيدة؟

المحلول

this throws stack overflow.

public override string ExternalId { set { ExternalId = value; } }

Because you are going into an infinite loop trying to set the property in the setter. If you are going to implement customized setter then you should get rid of auto-implemented property, Define a field and encapsulate that through your property.

For the other question

the base class CANNOT have external id, only some of the derived class use it and need to over ride.

That is why you have proctected access specifier. You can have it as protected like:

public abstract class MockDataBase
{
    private string _ExxternalID;

    public virtual string ExxternalID
    {
        get { return _ExxternalID; }
        protected set { _ExxternalID = value; }
    }
}
public class UnitMockDataBase : MockDataBase
{
    public override string ExxternalID
    {
        get
        {
            return base.ExxternalID;
        }
        protected set
        {
            base.ExxternalID = value;
        }
    }
}

نصائح أخرى

You are calling the set in an endless loop. To solve this problem change your code like this:

public class UnitMockDataBase: MockDataBase
{
    private string _externalId;
    public override string ExternalId 
    {
        get { return _externalId; } } 
        set { _externalId = value; } }
}

So when you set the id (e.g. myUnitMockDataBase.ExternalId = "some value") it changes the _externalId and finishs. But in this case:

public class UnitMockDataBase: MockDataBase
{
    public override string ExternalId { set { _externalId = value; } }
}

when you set the ExternalId (e.g. myUnitMockDataBase.ExternalId = "some value") it calls the set block and in your set block you are calling the set block again!

To see what is happening set a break point in the set and use the Call Stack and trace the code execution steps

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top