加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – “as”运算符的奇怪行为

发布时间:2020-12-15 07:55:28 所属栏目:百科 来源:网络整理
导读:所以我有以下代码: /// summary/// The 'Prototype' abstract class/// /summaryabstract class ColorPrototype{ public abstract ColorPrototype Clone();}/// summary/// The 'ConcretePrototype' class/// /summaryclass Color : ColorPrototype{ privat
所以我有以下代码:
/// <summary>
/// The 'Prototype' abstract class
/// </summary>
abstract class ColorPrototype
{
    public abstract ColorPrototype Clone();
}

/// <summary>
/// The 'ConcretePrototype' class
/// </summary>
class Color : ColorPrototype
{
    private int _red;
    private int _green;
    private int _blue;

    // Constructor
    public Color(int red,int green,int blue)
    {
        this._red = red;
        this._green = green;
        this._blue = blue;
    }

    // Create a shallow copy
    public override ColorPrototype Clone()
    {
        Console.WriteLine(
          "Cloning color RGB: {0,3},{1,{2,3}",_red,_green,_blue);

        return this.MemberwiseClone() as ColorPrototype;
    }
}

/// <summary>
/// Prototype manager
/// </summary>
class ColorManager
{
    private Dictionary<string,ColorPrototype> _colors =
      new Dictionary<string,ColorPrototype>();

    // Indexer
    public ColorPrototype this[string key]
    {
        get { return _colors[key]; }
        set { _colors.Add(key,value); }
    }
}

在我的主要方法中:

ColorManager colormanager = new ColorManager();

// Initialize with standard colors
colormanager["red"] = new Color(255,0);

// User clones selected colors
ColorPrototype p1 = colormanager["red"].Clone();
bool isColor = p1 is Prototype.Color;
Color color1 = p1 as Color;

我的问题是为什么变量p1的类型为Color(isColor为true),如果在clone方法中我将结果转换为ColorPrototype(将this.MemberwiseClone()作为ColorPrototype返回;)?

参考:http://www.dofactory.com/net/prototype-design-pattern

解决方法

if in the clone method I cast the result to ColorPrototype

因为即使将p1转换为ColorPrototype,p1的运行时类型仍为Color类型.转换引用类型允许您将类型T视为类型U,但它不会更改基础运行时类型.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读