开发者

Hiding the Set accessor

I have a base class, FooBase. On it are a few standard read/write properties. When i subclass this, i want the subclass to have only read properties. Is this possible?

class FooBase
{
    public virtual int ID{get; set;}
    public virtual 开发者_StackOverflow中文版string Name{get;set;}
}

class Foo : FooBase
{
   public override int ID {get;}
   public override string Name{get;}
}

I know that code doesnt work, but it might give you some idea what im after

Thanks!


You can't just remove a public member like that, or it will break anything that tries to treat a Foo object like a FooBase object.

You could try something like this:

public virtual string Name{get; protected set;}

Making the setter only available to classes derived from FooBase.


No. You have your class heirarchy the wrong way round.

The writable version should be a subclass of the readonly version. Here's one way you could do it:

class FooBase
{
    public int ID { get; protected set; }
    public string Name { get; protected set; }
}

class Foo : FooBase
{
    public void SetId(int id) { /* ... */ }
    public void SetString(string name) { /* ... */ }
}


This seems to provide answer to your question.

http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/768dc05e-db95-479d-b0a2-4fe478a47591

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜