首页 > 解决方案 > 如何使用受限于接口的泛型类型访问基类成员?

问题描述

在我的基类 ( 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");
    }
}

我不熟悉接口以及它们是如何实现的,所以我的天真可能会把我引向错误的方向。我如何重建我的代码以使其工作?

标签: c#interfacememberbase-classinterface-implementation

解决方案


推荐阅读