繁体   English   中英

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

[英]Unable to check type of entity of base/inherited classes

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

我有Content的基类和Podcast和AudioBook的继承类。

我使用的是Code First,并且每个层次结构都有一个表(该表将所有子类存储在一个带有Discriminator列的表中)来存储所有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");
}

我在这里缺少什么吗? 谢谢你的帮助。

参考: 类型检查:typeof,GetType,还是?

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

  • 选项1:

     if (content is Content) { //do code here } 
  • 选项2:

     if (content.GetType().IsSubclassOf(typeof(Content))) { //do code here } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM