我在使用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");
}
这里有什么我想念的吗?谢谢你的帮助 .
1 回答
GetType()
返回对象的实际类,因此如果您尝试将其与typeof(Content)
进行比较,则会得到false
. 但是,如果要检查变量是否派生自基类,我建议使用2个选项 .