首页 文章

无法检查基类/继承类的实体类型

提问于
浏览
0

我在使用GetType()和typeof()获取类的类型时遇到问题,问题是它无法正常工作 .

我有内容的基类和继承的 Podcast 和AudioBook类 .

我正在使用Code First并且每个层次结构都有一个表(它将所有子类存储在一个带有Discriminator列的表中)来存储所有Content实体 .

我想通过Title列查询Content表,并返回Content实体 . 然后,根据类型(Podcast,AudioBook)做一些其他的事情 . 但是类型检查不起作用 .

楷模

public abstract class Content
{ 
    public string Title { get; set; }
}

public class Podcast : Content
{

}

知识库

public Content FindContentByRoutingTitle(string routingTitle)
{
    var content = Context.ContentItems
    .FirstOrDefault(x => x.RoutingTitle == routingTitle);

    return content;
}

调节器

var content = _contentRepository.FindContentByRoutingTitle(title);

if (content.GetType() == typeof(Podcast))
{
    return RedirectToAction("Index", "Podcast", new { title = title });
}
else if (content.GetType() == typeof(Content))
{
    //just a check to see if equating with Content
    return RedirectToAction("Index", "Podcast", new { title = title });
}
else
{
    //if/else block always falls to here.
    return RedirectToAction("NotFound", "Home");
}

这里有什么我想念的吗?谢谢你的帮助 .

参考:Type Checking: typeof, GetType, or is?

1 回答

  • 4

    GetType() 返回对象的实际类,因此如果您尝试将其与 typeof(Content) 进行比较,则会得到 false . 但是,如果要检查变量是否派生自基类,我建议使用2个选项 .

    • 选项1:
    if (content is Content)
    {
         //do code here
    }
    
    • 选项2:
    if (content.GetType().IsSubclassOf(typeof(Content)))
    {
     //do code here
    }
    

相关问题