0

我希望使用继承将设置器添加到现有属性。我想做这样的事情:

public class MyObjectRepository<T> : IObjectRepository<T> where T : IRepositoryEntity
{
    private readonly List<T> _data = new List<T>();
    // ...
    public void Add(T model)
    {
        _data.Add(model);

        var managedModel = (IManagedRepositoryEntity)model;
        if (managedModel != null)
            managedModel.SetId(_data.LastIndexOf(model));
    }
    // ...
}

public interface IRepositoryEntity
{
    object Id { get; }
}

public interface IManagedRepositoryEntity : IRepositoryEntity
{
    void SetId(object id);
}

我猜这行得通,但我不喜欢那个SetId行业。我想做这样的事情,但是唉,C#不会让我:

public interface IRepositoryEntity
{
    virtual object Id { get; }
}

public interface IManagedRepositoryEntity : IRepositoryEntity
{
    override object Id { get; set; }
}
4

1 回答 1

1

virtual并且override在接口定义中无效,您需要

public interface IRepositoryEntity
{
   object Id { get; }
}

public interface IManagedRepositoryEntity : IRepositoryEntity
{
    new object Id { get; set; }
}
于 2013-09-13T19:43:58.167 回答