开发者

readonly property setter

开发者 https://www.devze.com 2022-12-28 07:09 出处:网络
After a extensive debugging session I found that the problem was that I called the setter of a readonly property. Is there a trick to provoke a compiler warning when this happens? Because marking the

After a extensive debugging session I found that the problem was that I called the setter of a readonly property. Is there a trick to provoke a compiler warning when this happens? Because marking the setter private does not work.

Cheers,

CA


To make clear what I mean:

    private readonly List<SomeObject> _budget;
    public IEnumerable<SomeObject> Budget
    {
 开发者_运维技巧       get
        {
            return _budget;
        }
    }

Can be accessed with

A.Budget=new SomeObject();

without compiler {error,warning,message}


You mixed something up here. In your example the compiler will yield an error if you try to do A.Budget=new SomeObject(); if the property Budget in class A does not have a setter. From here on I can only assume what your problem is.

My guess is that you would like the collection wrapped in the Budget property to be readonly. That's probably why you made it IEnumerable<SomeObject> whereas the private member is a List<SomeObject>. So even if you do do not have a setter you can still do (A.Budget as List<SomeObject>).Add(bla). To prohibit this you can use List.AsReadOnly like this:

private readonly List<SomeObject> _budget;
public ReadOnlyCollection<SomeObject> Budget
{
    get
    {
        return _budget.AsReadOnly();
    }
}


If your property has a setter, it isn't read-only. Remove the setter to make it read-only.

public string MyProperty // not read-only
{
    get { return myPropertyBacking; }
    set { myPropertyBacking = value; }
}

public string MyProperty // read-only
{
    get { return myPropertyBacking; }
}


Remove the setter.


As it is it doesn't make sense but if you meant something like this for your example...

private readonly List<SomeObject> _budget;
public List<SomeObject> Budget
{
    get
    {
        return _budget;
    }
}

Can be accessed with

A.Budget.Add(new SomeObject());

That would work without error.

EDIT

bitbonk's latest edit is exactly where I was going with this! I was just waiting for confirmation of the problem.

0

精彩评论

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

关注公众号