如何使用受限于接口的泛型访问基类成员?

时间:2019-05-02 19:53:59

标签: c# interface member base-class interface-implementation

在基类(Entity)中,我实现了由接口(GetEntity)定义的方法(IEntity)。该方法适用于受限于接口类型的通用类型(TEntity)。在上述方法中,我想采用通用类型并将其强制转换为基类类型,以访问基类中定义的成员(ParentKeyFields)。这是代码:

public interface IEntity
{
    TEntity GetEntity<TEntity>(string identifier) where TEntity : IEntity;
}

public class Entity : IEntity
{
    private readonly IDataProvider DataProvider;
    private readonly IUserContext UserContext;

    public List<string> ParentKeyFields { get; set; }

    public Entity(IDataProvider dataProvider, IUserContext userContext)
    {
        // ...

        ParentKeyFields = new List<string>();
    }

    public TEntity GetEntity<TEntity>(string identifier) where TEntity : IEntity
    {
        // Approach #1:
        TEntity result = default(TEntity);
        List<string> test = ((Entity)result).ParentKeyFields;
        // This gives me an error saying: "Cannot conver type 'TEntity' to 'Entity'".

        // Approach #2:
        Entity result = (TEntity) new Entity(DataProvider, UserContext);
        // This gives me an error saying: "Cannot convert type 'Entity' to 'TEntity'.
        List<string> test = result.ParentKeyFields;
        return result;
        // This gives me an error saying: "Cannot implictly convert type 'Entity' to 'TEntity'".
    }
}

我无法访问该成员(ParentKeyFields)。我尝试过在对象创建和访问成员时进行强制转换。两种方法都无法编译。

我想访问该成员中为不同派生类型定义的不同值:

class Company : Entity
{
    public Company(IDataProvider dataProvider, IUserContext userContext) : base(dataProvider, userContext)
    {
    }
}

public class Employee : Entity
{
    public Employee(IDataProvider dataProvider, IUserContext userContext) : base(dataProvider, userContext)
    {
        ParentKeyFields.Add("co");
    }
}

public class EIns : Entity
{
    public EIns(IDataProvider dataProvider, IUserContext userContext) : base(dataProvider, userContext)
    {
        ParentKeyFields.Add("co");
        ParentKeyFields.Add("id");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Entity test = system.GetEntity<Employee>("foobar");
    }
}

我对接口及其实现方式还是陌生的,所以我的幼稚可能将我引向错误的方向。我该如何重构我的代码才能使它正常工作?

0 个答案:

没有答案