使用base中的方法创建对象会导致错误无法强制转换

时间:2017-10-11 09:10:52

标签: c#

我有带有受保护构造函数的类和一个公共静态创建方法。我已经在基类中有这样的方法。是否可以在儿童班中使用它? 现在我有:

基类:

public class Screening : CandidateEvent
{
    protected Screening() { }
    protected Screening(Guid id) : base(id) { }
    public static Screening Create(DateTime plannedDate, PeriodDateTime period, String summary)
    {
        Screening screening = new Screening(Guid.NewGuid());
        screening.PlannedDate = plannedDate;
        screening.Period = period;
        screening.Summary = summary;
        // checks the params
        return screening;
    }
}

儿童班:

public class EmailScreening : Screening
{
    protected EmailScreening() { }
    protected EmailScreening(Guid id) : base(id) { }
    public new static EmailScreening Create(DateTime plannedDate, PeriodDateTime period, String summary)
    {
        EmailScreening emailScreening = (EmailScreening)Screening.Create(plannedDate, period, summary);
        return emailScreening;
    }
}

并测试:

[TestClass]
public class EmailScreeningTest
{
    [TestMethod]
    public void TestCreate()
    {
        PeriodDateTime period = new PeriodDateTime(new DateTime(2017, 01, 01), new DateTime(2017, 02, 02));
        EmailScreening emailscreening = EmailScreening.Create(new DateTime(2017,11,05), period, "summary");

        Assert.AreEqual(emailscreening.PlannedDate, new DateTime(2017, 11, 05));
        Assert.AreEqual(emailscreening.Period, period);
        Assert.AreEqual(emailscreening.Summary, "summary");
    }  
}

但是测试失败说无法将'Screening'类型的对象转换为'EmailScreening'类型。

那么,有没有办法在我的子类中使用基本方法并获得正确的对象?

0 个答案:

没有答案