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

12

在我们的.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); }
    }
}

6
我个人会首先将该字段设为私有。你真的需要将该字段保护起来吗? - Jon Skeet
3
改将字段命名为_distance,对吗? - Visual Vincent
7
我会将字段设为私有并在属性上添加 protected 的 setter 方法。 - Fabjan
2
@Alberto 使用 _m 前缀可以消除歧义和 IntelliSense 错误。 - Zein Makki
2
我个人会使用两个属性,AbsoluteDistance 和(受保护的)RawDistance 或类似的名称。 - Jon Skeet
显示剩余4条评论
2个回答

22

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

要使设置属性仅对继承类可访问,请使用受保护的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);
    }
}

7
受保护的成员字段最初是设计用于什么目的? - abenci
4
某事物可能存在并不意味着它应该被使用。 - Wicher Visser
1
@WicherVisser 在这个上下文中,版本控制 是什么意思? - silkfire
用词不当。我是指“更改”:将内部更改为类。 - Wicher Visser

3
好的,根据已经说过的内容,您可以这样做:

首先,您需要这样设置:

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设置值,因此在"AbsoluteDistance"的getter中不需要调用Math.Abs()

1
我愿意工作,但它太复杂且难以维护。感谢您的努力... - abenci

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接