implementing a read/write field for an interface that only defines read
I have a C# 2.0 application where a base interface allows read-only access to a value in a concrete class. But, within the concrete class, I'd like to have read/write access to that 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 the error:
Foo.cs(200,22): error CS0546: 'Foo.StartTime.set': cannot override because 'Base.StartTime' does not have an overridable set accessor
I don't want the base class to have write access. But, I do want the concrete class to provide read/write access. Is there a way to make this work?
Thanks, PaulH
Unfortunately, Base
can't be changed to an interface as it contains non-abstract functionality also. Something I should have thought to put in the original problem description.
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;
}
开发者_如何学编程}
It's not as nice as I'd like, but it works.
Any reason to not use an interface over the abstract class?
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; }
}
}
You can do it this way:
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;
}
}
}
Optionally, use an interface.
You can't do this when deriving from a base class, but you can do it when implementing an interface.
So if you can replace your base class with an interface instead then it will work.
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;
}
}
It's not as nice as I'd like, but it works.
精彩评论