Implement a read / write field for an interface that defines read only

I have a C # 2.0 application where the base interface allows read-only access to a value in a particular class. But in a particular class, I would like to have read and write access to this value. So, I have an implementation like this:

public abstract class Base
{
    public abstract DateTime StartTime { get; }
}

public class Foo : Base
{
    DateTime start_time_;

    public override DateTime StartTime
    {
        get { return start_time_; }
        internal set { start_time_ = value; }
    }
}

But this gives me an error:

Foo.cs(200,22): error CS0546: 'Foo.StartTime.set': cannot override because 'Base.StartTime' does not have an overridable set accessor

I do not want the base class to have write access. But I want a specific class to provide read / write access. Is there any way to make this work?

Thanks PaulH


Unfortunately, Baseit cannot be changed to an interface, since it also contains non-abstract functionality. Something I had to think about in order to provide an initial description of the problem.

public abstract class Base
{
    public abstract DateTime StartTime { get; }

    public void Buzz()
    {
        // do something interesting...
    }
}

My solution is to do this:

public class Foo : Base
{
    DateTime start_time_;

    public override DateTime StartTime
    {
        get { return start_time_; }
    }

    internal void SetStartTime
    {
        start_time_ = value;
    }
}

, , .

+3
4

, :

public class Foo : Base
{
    DateTime start_time_;

    public override DateTime StartTime
    {
        get { return start_time_; }
    }

    internal void SetStartTime
    {
        start_time_ = value;
    }
}

, , .

0

?

    public interface Base
    {
        DateTime StartTime { get; }
    }

    public class Foo : Base
    {
        DateTime start_time_;

        public DateTime StartTime
        {
            get { return start_time_; }
            internal set { start_time_ = value; }
        }
    }
+3

You can do it as follows:

public abstract class Base
{
    public abstract DateTime StartTime { get; internal set; }
}
public class Foo : Base
{
    DateTime start_time_;
    public override DateTime StartTime
    {
        get
        { 
            return start_time_; 
        }
        internal set
        {
            start_time_ = value;
        }
    }
} 

Additionally, use the interface.

+1
source

You cannot do this when getting the base class, but you can do it when implementing the interface.

So, if you can replace the base class with an interface, then it will work.

0
source

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


All Articles