继承中使用接口的类型转换问题

3

我有以下模型:

public interface IAntiSpam {
    string Name { get; }
    string Text { get; }
}

public interface IAntiSpamSubclass<T> where T : IAntiSpam {
    T Entity { get; set; }
}

public class Comment : IAntiSpam {
    public string Name { get; set; }
    public string Text { get; set; }
}

public class ForumPost : IAntiSpam {
    public User User { get; set; }
    public string Text { get; set; }
    public string Name { get return User.Name; }
}

public class ReportedData {        
    public string Reason { get; set; }
    public User ReportedBy { get; set; }
    public DateTime DateReported { get; set; }
}

public class CommentReported : ReportedData, IAntiSpamSubclass<Comment> {        
    public Comment Entity { get; set; }
}

public class ForumPostReported : ReportedData, IAntiSpamSubclass<ForumPost> {        
    public ForumPost Entity { get; set; }
}

这个编译通过,我认为这是我走在正确道路上的标志。

现在,给定一个ReportedData列表,我需要循环遍历数据并显示报告数据的Text属性。我可以将ReportedData强制转换为适当的类型,然后从那里访问它。但是,我不想这样做,因为我需要能够添加继承自ReportedData的其他类型,而无需修改显示Text属性的代码。这就是我想到使用接口的地方。

这是我尝试运行的代码:

var reportedData = GetReportedData(); // Returns IList<ReportedData>()

foreach (var data in reportedData) {
    var text = ((IAntiSpamSubclass<IAntiSpam>)data).Entity.Text;
}

然而,运行时出现以下错误:
无法将类型为“CommentReported”的对象转换为类型“IAntiSpamSubclass`1 [IAntiSpam]”。
如果有人能帮助我找出错误所在,我将不胜感激。谢谢。
1个回答

2

谢谢。我一直想学习这方面的知识,这让我有了一个很好的开始。再次感谢,非常感激。 - nfplee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接