as的奇怪行为操作符
本文关键字:操作符 as | 更新日期: 2023-09-27 18:13:07
所以我有以下代码:
/// <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,3},{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); }
}
}
在main方法中我有:
ColorManager colormanager = new ColorManager();
// Initialize with standard colors
colormanager["red"] = new Color(255, 0, 0);
// User clones selected colors
ColorPrototype p1 = colormanager["red"].Clone();
bool isColor = p1 is Prototype.Color;
Color color1 = p1 as Color;
我的问题是为什么变量p1具有类型Color
(isColor
是真的),如果在克隆方法中我将结果转换为ColorPrototype
(return this.MemberwiseClone() as ColorPrototype;
) ?
参考:http://www.dofactory.com/net/prototype-design-pattern
this.MemberwiseClone()
返回Color
对象。所以p1
实际上是Color
。
如果向上转换为ColorPrototype
则无关紧要。它的运行时类型仍然是Color
。这相当于:
string s = "foo";
object o = s as object;
// runtime o type is still string
如果在clone方法中我将结果强制转换为ColorPrototype
因为即使您将p1
强制转换为ColorPrototype
, p1
的运行时类型仍然是Color
类型。强制转换引用类型允许您将类型T
视为类型U
,但它不会改变底层运行时类型。