"如" c#中的关键字返回空数据

时间:2014-09-26 14:00:44

标签: c#

在使用关键字" as"时,如何将基类数据放入子类对象中。我尝试了下面的代码,但它返回了空数据。

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;
    }
}

4 个答案:

答案 0 :(得分:4)

这是 的行为:

您的代码(简化):

 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; 

答案 1 :(得分:3)

这不会奏效。将BaseC替换为Animal,将DerivedC替换为Cow,您就会知道原因。

运行时无法从Cow的实例创建Animal,因为缺少信息。这将有效:

BaseC baseC = new DerivedC();

因为实例实际上是一个DerivedC

答案 2 :(得分:0)

baseC不是DerivedC的实例,因此as运算符将始终返回null

但如果您将Main的第一行更改为:

,则会有效
BaseC baseC = new DerivedC();

答案 3 :(得分:0)

至于一个实用的解决方案(也许你在尝试 as 关键字之前已经这样做了,但我想我会把它扔出去):< / em>的

如果您所有可用的是基本实例(并且由于某种原因无法更改),并且您想要填充派生实例,您可以考虑添加一个接受该实例的构造函数基类作为参数:

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);

至少可以减少代码重复,因此您不会在多个位置手动分配值。