是否有可能两个不同的 类 有一个 属性 - 类 的集合并且每个对象都知道它属于前两个 类 中的哪一个?

Is it possible that two different classes have a property -a collection of classes and each object knows which of the first two classes it belongs to?

我还有下3个类

class Review
{
   public int Id{get; set;}
   public string Text{get; set;}
   public ICollection<Comment> Comments{get; set;}
//some additional properties
}
class User
{
   public int Id{get; set;}
   public string Name{get; set;}
   public string Login{get; set;}
   public ICollection<Comment> Comments{get; set;}
//some additional properties
}
class Comment
{
   public int Id{get; set}
   public string Comment{get; set;}
   public ??? Target{get; set;}
}

在此上下文中,目标是评论所附加的内容。对于某些事情,我需要确切地知道目标是谁——特定用户或特定评论。 由于参数的强烈区分,从接口继承是不合适的。我需要使用数据库,所以对象类型不适用于那种情况(据我所知)。

根据提供的代码,您可以将 objectdynamic 用于 Target

但是你可能更喜欢使用基数 class 作为 ReviewUserBaseObjectWithComments 这样能够写成 BaseObjectWithComments Target,这有点更好。

所以我们可以将一些成员移动到这个根 class。

我们还可以为 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

关于使用数据库,需要更改设计。

例如 table 的字段可能是这样的:

CommentID
ReviewID
UserID
Text

但这并不干净,因此您可能更愿意使用 2 个 table 更符合惯例:UserCommentsReviewComments,因此每个 table s 将有一个 OwnerID 指向 UsersReviews.

因此,您可以在前面 classes 的实例中加载数据,同时按照指示设置所有者引用。

也许您可以考虑使用 ADO.NET 类型的数据集,它可以为您完成所有工作,同时能够使用 Visual Studio RAD Designers:

Typed DataSets (MS Docs)

How to: Create and configure datasets in Visual Studio (MS Docs)

Beginning C# 2005 Databases (Wrox)