【问题标题】:C#: naming rules for protected members fieldsC#:受保护成员字段的命名规则
【发布时间】:2016-07-08 12:12:39
【问题描述】:

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

【问题讨论】:

  • 我会亲自将该字段设为私有。为什么你真的需要保护这个领域?
  • 改为将字段命名为_distance
  • 我仍将字段设为 private 并将 protected setter 添加到属性中
  • @Alberto _m 前缀用于消除歧义和智能感知错误。
  • 我个人可能有两个属性。 AbsoluteDistance 和(受保护的)RawDistance 或类似的东西。

标签: c# .net naming-conventions


【解决方案1】:

您不应使用受保护的字段,因为无法保护版本控制和访问。请参阅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);
    }
}

【讨论】:

  • 当时受保护的成员字段是为什么设计的?
  • 某事可能的事实并不意味着它应该被使用。
  • @WicherVisser versioning 在这种情况下是什么意思?
  • 选词不当。我的意思是“改变”:改变班级内部。
【解决方案2】:

嗯,总结一下已经说过的话,你可以做这样的事情:

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()

【讨论】:

  • 我会工作,但它太复杂且难以维护。感谢您的努力...
猜你喜欢
  • 2017-06-01
  • 1970-01-01
  • 2016-06-12
  • 2014-06-09
  • 2020-01-31
  • 1970-01-01
  • 2011-03-12
  • 2023-03-03
  • 1970-01-01
相关资源
最近更新 更多