从提供的代码中,您可以使用object 或dynamic 作为Target。
但您可能更喜欢使用Review 和User 的基类,例如BaseObjectWithComments,以便能够编写BaseObjectWithComments Target,这样会好一些。
所以我们可以将一些成员移动到这个根类。
我们还可以为Comment添加一个构造函数来传递所有者。
public abstract class BaseObjectWithIdAndComments
{
public int ID { get; set; }
public ICollection<Comment> Comments { get; set; }
}
public class Review : BaseObjectWithIdAndComments
{
public string Text { get; set; }
}
public class User : BaseObjectWithIdAndComments
{
public string Name { get; set; }
public string Login { get; set; }
}
public class Comment
{
public int ID { get; set; }
public string Text { get; set; }
public BaseObjectWithIdAndComments Target { get; set; }
public Comment(BaseObjectWithIdAndComments owner, int id, string comment)
{
Target = owner;
ID = id;
Text = comment;
}
}
测试
var review = new Review();
var user = new User();
review.Comments = new List<Comment>();
user.Comments = new List<Comment>();
review.Comments.Add(new Comment(review, 1, "review comment 1"));
review.Comments.Add(new Comment(review, 2, "review comment 2"));
user.Comments.Add(new Comment(user, 1, "user comment 1"));
user.Comments.Add(new Comment(user, 2, "user comment 2"));
Console.WriteLine("Owner of review comment #1: " + review.Comments.ElementAt(0).Target.GetType().Name);
Console.WriteLine("Owner of user comment #2: " + user.Comments.ElementAt(1).Target.GetType().Name);
输出
Owner of review comment #1: Review
Owner of user comment #2: User
关于使用数据库,您需要更改设计。
例如表格的字段可能是这样的:
CommentID
ReviewID
UserID
Text
但这并不干净,因此您可能更喜欢有 2 个表以更常规:UserComments 和 ReviewComments,因此这些表中的每一个都有一个 OwnerID 指向 Users 或 Reviews .
因此,您可以在设置所有者引用的同时加载先前类的实例中的数据。
也许您可以考虑使用 ADO.NET 类型的数据集,它可以为您完成所有工作,同时能够使用 Visual Studio RAD 设计器:
Typed DataSets (MS Docs)
How to: Create and configure datasets in Visual Studio (MS Docs)
Beginning C# 2005 Databases (Wrox)