Override only

I got an abstract class:

abstract class ClassBase
    {
        public abstract string Test { get; }
    }

I want to get it and, by the way, add a set of accesor

 class ClassDerive : ClassBase
    {
        string _s;

        public override string Test
        {
            get { return _s; }
            set { _s = value; }
        }
    }

I cannot do this because I cannot override set

 class ClassDerive2 : ClassBase
    {
        string _s;

        public string Test
        {
            override get { return _s; }
            set { _s = value; }
        }
    }

Syntax error

class ClassDerive3 : ClassBase
{
    string _s;

    public override string ClassBase.Test
    {
        get { return _s; }
    }

    public string Test
    {
        set { _s = value; }
    }
}

Syntax error

Any idea ???

THX

+3
source share
5 answers

If you first defined the read-only property in the type, you cannot subsequently change it to the read / write property in the derived class. This is just how .NET works and cannot be changed.

If, on the other hand, you define an interface with a read-only property, you can later implement this interface in a writable class.

If you want to share what you are trying to achieve, perhaps we can develop a project that works and can compile :)

+3

, , :

abstract class ClassBase
{
    public abstract String Test { get; }
}

class ClassDerive : ClassBase
{
    string _s;

    public override string Test
    {
        get { return _s; }
    }

    public void SetTest(String test)
    {
        this._s = test;
    }
}

Test ClassDerived SetTest. , , , , .

+6

Another way:


    abstract class ClassBase
    {
        public abstract string Test { get; }
    }

    class ClassDerive : ClassBase
    {
        string _s;
        protected void setTest(string s)
        {
            _s = s;
        }

        public override string Test
        {
            get { return _s; }
        }
    }

    class ClassDerive2 : ClassDerive
    {
        public new string Test
        {
            get { return base.Test; }
            set { setTest(value); }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var cd2 = new ClassDerive2();
            cd2.Test = "asdf";
            Console.WriteLine(cd2.Test);
        }
    }
+2
source

No, you can’t, sorry. This is by design, so this is the law.

+1
source

My first thought was to implement it as an interface. If it matches your design, the following code will work:

public interface TestInterface
{
   string TestProperty { get; }
}

public class TestClass : TestInterface
{
   public string TestProperty
   {
      get { return "test"; }
      set { string t = value; }
   }
}
+1
source

Source: https://habr.com/ru/post/1711263/


All Articles