继承接口,以便将setter添加到现有属性

时间:2013-09-13 19:40:40

标签: c# inheritance interface repository

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

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; }
}

1 个答案:

答案 0 :(得分:1)

virtualoverride在接口定义中无效,您需要

public interface IRepositoryEntity
{
   object Id { get; }
}

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