【问题标题】:Reverse Extending a Class反向扩展类
【发布时间】:2014-06-11 23:20:18
【问题描述】:

我正在尝试创建一个“反向”扩展 Rectangle 的类。我希望能够把这个方法放在类中:

    public Point RightPoint()
    {
        return new Point(this.X + this.Width, this.Y + this.Height / 2);
    }

然后拨打rectangle.RightPoint();并获取返回值。 (XYWidthHeightRectangle 的字段。

这可能吗?还是我需要制作这些静态方法,然后将它们传递给Rectangle

【问题讨论】:

    标签: c# inheritance static extend rectangles


    【解决方案1】:

    如果您想向现有类添加方法,您的选择是:

    1. 为 Rectangle 类编写扩展方法。
    2. 从 Rectangle 类继承,并将您的方法添加到子类。
    3. 将成员直接添加到 Rectangle 类中。

    选项 #2 需要创建一个新类型,选项 #3 需要您更改类。我会推荐这样的扩展方法:

    public static Point RightPoint(this Rectangle rect)
    {
        return new Point(rect.X + rect.Width, rect.Y + rect.Height / 2);
    }
    

    这将允许您拨打您想要的电话:

    var rectangle = new Rectangle();
    var point = rectangle.RightPoint();
    

    【讨论】:

      【解决方案2】:

      您可以使用扩展方法:

      public static class ExtensionMethods
      {
          public static Point RightPoint(this Rectangle rectangle)
          {
              return new Point(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height / 2);
          }
      }
      

      这将允许您像使用 Rectangle 结构一样使用它:

      Point rightPoint = rect.RightPoint();
      

      【讨论】:

        【解决方案3】:

        我认为您需要extension method

        public static Point RightPoint(this Rectangle rectangle)
        {
            return new Point(rectangle.X + rectangle.Width, rectangle.Y + rectangle.Height / 2);
        }
        

        上面的代码应该放在static 类中。

        然后您可以在 Rectangle 对象上执行此操作:

        Rectangle rect = new Rectangle();
        Point pointObj = rect.RightPoint();
        

        【讨论】:

        • @Evorlor,很高兴能帮上忙。
        • 我能在房产中做到这一点吗? (所以我不需要方法调用后的括号)
        • @Evorlor,不,你可以这样做。
        猜你喜欢
        • 2012-05-29
        • 2019-05-19
        • 2017-06-05
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-14
        • 2011-11-22
        相关资源
        最近更新 更多