2

让我举一个很好的例子来说明我的问题。

假设我正在构建一个应用程序,许多用户可以在其中发布不同类型的“帖子”(即照片、状态等)。对于这种情况,我们只使用照片和状态。

我将向您展示我当前如何对数据进行建模,以及是否可以改进(以及我做错了什么)

我有一个通用的 Post 类:

public class Post<T>
{
    public Guid Id { get; set; }

    public User Owner { get; set; }

    public DateTime CreatedDate { get; set; }

    public PostType Type { get; set; }

    public T Data { get; set; }
}

然后我有一个 PostType 枚举:

public enum PostType
{
    Photo,
    Status
}

然后我有我各自的照片和状态类

public class Photo
{
    public string Url { get; set; }

    public int Width { get; set; }

    public int Height { get; set; }
}

public class Status
{
    public string Text { get; set; }
}

我知道,如果我追求当前的解决方案来建模这些数据,我会遇到问题。

我已经遇到了一些痛点,例如如何返回最新的 25 个帖子,无论类型如何,以及如何在不指定帖子类型的情况下按 Id 返回特定帖子(因为用户不应该关心。

我是否完全错误地建模了我的数据?如果是这样,您有什么改进的建议吗?

4

2 回答 2

1

您的两个问题都可以通过拥有一个独立于帖子类型的基类来解决:

public abstract class Post
{
    public Guid Id { get; set; }

    public User Owner { get; set; }

    public DateTime CreatedDate { get; set; }

    public PostType Type { get; set; }
}

然后你的Post类可以继承它:

public class Post<T> : Post
{
    public T Data { get; set; }
}

应该返回任何类型的 post 的方法仍然可以返回正确的类型,但调用者会将它们作为基本Post类型访问并在需要时强制转换它们:

Post GetPostById(int id);
IEnumerable<Post> GetLatestPosts(int count);
于 2012-11-19T05:57:09.540 回答
0

无论类型如何,我如何返回最新的 25 个帖子

你不能,因为在你的设计中 aPhoto和 a之间没有共同点Status,你有一个 generic Post<T>,但是这里Ts 不能批量进行。更好的设计应该是这样的:

public interface IPostable
{
    Guid Id { get; set; }

    public DateTime CreatedDate { get; set; }

    PostType PostType { get; }
}

public class Photo : IPostable
{
    //special properties for photo
    public string Url { get; set; }

    //implement the interface
    public PostType PostType { get { return PostType.Photo; } }
}

public class Status : IPostable
{
    public string Text { get; set; }
    public PostType PostType { get { return PostType.Status; } }
}

然后你总是IPostable分批处理。

如何按 Id 返回特定的帖子

根据上面的设计,你可以很容易的IPostable通过id获取实例,因为id是它的属性之一,通过判断PostType属性返回强类型实例:

public IPostable GetPost(Guid id)
{
    //id is a property of IPostable, so everything is easy
}

//you can easily get the real type
public T GetPost<T>(Guid id)
{
    IPostable post = GetThePostFirst();
    if (post.PostType == PostType.Photo) return (Photo)IPostable;
    //etc.
}
于 2012-11-19T06:14:55.620 回答