Overridable Methods In Constructors -Help to Fix

半城伤御伤魂 提交于 2019-12-11 09:03:37

问题


Im attempting to use fxCop on a C# Project as kind of basis for C# coding standards.

The project Im using is called S#arp Architecture and is freely available here: S#Arp Arch

Now if I run fxCop (most things have been fixed already) I need to fix the CA2214 fxcop error for overridable methods in contructors.

At the moment a piece of violating code looks like this:

public class Region : Entity, IHasAssignedId<int>
{
    public Region(string description)
    {
        Check.Require(!string.IsNullOrEmpty(description));
        this.Description = description;
    }

    protected Region()
    {
    }

    [DomainSignature]
 >  public virtual string Description { get; protected set; }

    public virtual void SetAssignedIdTo(int assignedId)
    {
        Id = assignedId;
    }
}

Most of it is called in this way in the other cd files:

public static RegionDto Create(Region region)
{
    if (region == null)
    {
        return null;
    }

    return new RegionDto()
    {
        Id = region.Id,
    >   Description = region.Description
    };
}

I have tried changing the type of method (private/protected etc) but there is often conflicting needs by fxCop and the unit tests, fxcop saying it doesnt like contructors with virtual methods but the unit saying that the methods should be public/protected virtual or protected internal virtual, catch 22 a lil bit?

So any help to fix this fxcop rule would be appreciated, thanks.

(The error occurs on the line marked with a >, the virtual get set method and when changed the other > is where it complains)


回答1:


This is easy: "don't do that". Instead:

private string _description;
public Region(string description)
{
    Check.Require(!string.IsNullOrEmpty(description));
    _description = description;
}

protected Region()
{
}

[DomainSignature]
public virtual string Description {
    get {return _description;} 
    set {_description = value;}
}


来源:https://stackoverflow.com/questions/1152960/overridable-methods-in-constructors-help-to-fix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!