• Effective C# 学习笔记(九) 在你的API中避免使用类型转换运算


    这里说的转换包括隐式和显示两种转换方式,这两种转换行为都会影响到其转换后行为。

    如:有一个类Shape,其作为Circle Ellipse两个类的基类。

     

    代码如下:

    //圆形类

    public class Circle : Shape

    {

    private PointF center;

    private float radius;

    public Circle() : this(PointF.Empty, 0)

    {

    }

    public Circle(PointF c, float r)

    {

    center = c;

    radius = r;

    }

    public override void Draw()

    {

    //...

    }

    //这里“隐式地”定义了圆形到椭圆的转换方法,即用圆形的原点和半径属性重新定一个椭圆对象返回

    static public implicit operator Ellipse(Circle c)

    {

    return new Ellipse(c.center, c.center,c.radius, c.radius);

    }

    }

    //对于结算面积的方法是没有问题的

    public static double ComputeArea(Ellipse e)

    {

    // return the area of the ellipse.

    return e.R1 * e.R2 * Math.PI;

    }

    // call it:

    Circle c1 = new Circle(new PointF(3.0f, 0), 5.0f);

    ComputeArea(c1);

     

    //但对于压扁的方法就出现了问题

    public static void Flatten(Ellipse e)

    {

    e.R1 /= 2;

    e.R2 *= 2;

    }

    // call it using a circle:

    Circle c = new Circle(new PointF(3.0f, 0), 5.0f);

    //由于使用了隐式转换,这时圆会转化为椭圆对象传入Flatten方法,但是这只是个创建新的椭圆对象,而不是原来的Circle类对应的圆了,所以对c压扁操作并不起作用

    Flatten(c);

     

    //所以需要保存转换后的椭圆对象,代码如下:

    // Work with the circle.

    // ...

    // Convert to an ellipse.

    Ellipse e = new Ellipse(c);

    Flatten(e);

  • 相关阅读:
    天文望远镜(二)
    天文望远镜(一)
    安静
    JavaScript 私有类字段和 TypeScript 私有修饰符
    js解析剪切板里的excel内容
    js正则
    jquery扩展方法:实现模拟Marquee无限循环滚动
    js中onload和ready区别
    Js如何从字符串中提取数字?
    JSBridge 初探
  • 原文地址:https://www.cnblogs.com/haokaibo/p/2097710.html
Copyright © 2020-2023  润新知