【发布时间】:2012-11-24 12:40:38
【问题描述】:
我的演示代码如下:
class Base
{
}
class SubA:Base
{
private int propertyA;
public int PropertyA
{
get{return propertyA}
}
}
class SubB:Base
{
private string propertyB;
public string PropertyB
{
get{return propertyB}
}
}
class Program
{
public void Action(Base obj)
{
//here i wanna use PropertyB if the ture obj is an instance of SubB.
// use PropertyA if the true obj is an instance of SubA
}
}
我传递给函数“Action”的真正对象是 SubB 或 SubA 的一个实例。我想访问“Action”中的PropertyB(如果SubB)或PropertyA(如果SubA)。我是否违反了一些基本的 OO 规则?处理这种情况的最佳方法是什么(我不想使用 C# 关键字 As 和 Is 来测试我转移的 obj)。我现在完全糊涂了。非常感谢任何建议或帮助。
【问题讨论】: