C#:受保护成员字段的命名规则

C#: naming rules for protected members fields

在我们的 .NET 软件组件中,我们使用以下命名约定。当客户从 VB.NET 使用我们的 DLL 时,编译器无法区分 distance 成员字段与 Distance 属性。您推荐什么解决方法?

谢谢。

public class Dimension : Text
{
    private string _textPrefix;

    protected double distance;

    /// <summary>
    /// Gets the real measured distance.
    /// </summary>
    public double Distance
    {
        get { return Math.Abs(distance); }
    }
}

您不应使用受保护的字段,因为无法保护版本控制和访问。请参阅 Field Design 准则。将您的字段更改为 属性,这也会强制您更改为名称(因为您不能拥有两个具有相同名称的属性)。或者,如果可能,将受保护字段设为私有。

要使 属性 的设置仅供继承 类 访问,请使用受保护的 setter:

public class Dimension : Text
{
    private string _textPrefix;

    private double _absoluteDistance;

    /// <summary>
    /// Gets the real measured distance.
    /// </summary>
    public double Distance
    {
        get { return _absoluteDistance  }
        protected set { _absoluteDistance = Math.Abs(distance); }
    }
}

虽然这确实会导致 get 和 set 之间的差异,因为功能不一样。在这种情况下,单独的受保护方法可能会更好:

public class Dimension : Text
{
    private string _textPrefix;

    /// <summary>
    /// Gets the real measured distance.
    /// </summary>
    public double Distance { get; private set; }

    protected void SetAbsoluteDistance(double distance)
    {
        Distance = Math.Abs(distance);
    }
}

好吧,总结一下已经说过的话,你可以这样做:

public class Dimension : Text
{
    private string _textPrefix;

    private double _rawDistance;

    /// <summary>
    /// Gets the real measured distance.
    /// </summary>
    public double AbsoluteDistance
    {
        get; private set;
    }

    /// <summary>
    /// Gets the raw distance
    /// </summary>
    public double RawDistance
    {
        get { return _rawDistance; }
        protected set { _rawDistance = value; AbsoluteDistance = Math.Abs(value); }
    }
}

设置 RawDistance 的值时,它也会设置 AbsoluteDistance 的值,因此不需要在 getter 中调用 Math.Abs() 19=]。