";作为“;c中的关键字返回空数据
本文关键字:关键字 返回 数据 quot 作为 | 更新日期: 2023-09-27 18:24:43
使用关键字as
时,如何将基类数据获取到子类对象中。我尝试了下面的代码,但它返回了null
数据。
class BaseC
{
public int BaseId { get; set; }
public string BaseName { get; set; }
}
class DerivedC: BaseC
{
public int DerivedId { get; set; }
public string DerivedName { get; set; }
}
class Program
{
static void Main(string[] args)
{
BaseC baseC = new BaseC();
baseC.BaseId = 1;
baseC.BaseName = "base class name ";
var derivedC = baseC as DerivedC;
}
}
没错作为行为:
您的代码(简化):
BaseC baseC = new BaseC();
// null: result is a BaseC instance and not DerivedC one
DerivedC result = baseC as DerivedC;
反向代码(可能是您期望看到的):
BaseC baseC = new DerivedC(); // <- Now, DerivedC instance created
// not null: result is in fact a DerivedC instance: new DerivedC()
DerivedC result = baseC as DerivedC;
// not null: DerivedC is inherired from BaseC
// and that's why any DerivedC instances are BaseC instances as well
BaseC result2 = baseC as BaseC;
这行不通。用Animal
替换BaseC
,用Cow
替换DerivedC
。
运行时无法从Animal
的实例创建Cow
,因为缺少信息。这将起作用:
BaseC baseC = new DerivedC();
因为实例实际上是一个DerivedC
。
baseC
不是DerivedC
的实例,因此as
运算符将始终返回null
。
然而,如果您将Main
的第一行更改为:,它会起作用
BaseC baseC = new DerivedC();
至于一个实用的解决方案(也许在尝试as
关键字之前就已经在做了,但我想我会把它扔出去):
如果您只有一个基类(由于某些原因无法更改),并且您想要填充派生实例,则可以考虑添加一个接受基类作为参数的构造函数:
class DerivedC : BaseC
{
public DerivedC() {} // req'd so you can still create an instance without a BaseC
public DerivedC(BaseC baseC)
{
BaseId = baseC.BaseId;
BaseName = baseC.BaseName;
}
public int DerivedId { get; set; }
public string DerivedName { get; set; }
}
然后这样称呼它:
var derivedC = new DerivedC(baseC);
至少这样可以减少代码重复,这样就不会在多个位置手动分配值。