c# - 如何使用受限于接口的泛型类型访问基类成员?
问题描述
在我的基类 ( 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");
}
}
我不熟悉接口以及它们是如何实现的,所以我的天真可能会把我引向错误的方向。我如何重建我的代码以使其工作?
解决方案
推荐阅读
- python - 正则表达式:将“空白”字符和 - 字符更改为 null
- javascript - Barba Js 在第一次链接上重新加载页面
- html - 如何使用引导程序将 div 向右对齐?
- r - R 中的代码可读性:如何避免 get() 和 assign()
- c# - ReSharper NUnit3 - 使用没有复制本地副本的 dll
- python - Pytorch NLP 模型在进行推理时不使用 GPU
- javascript - 如何在函数外传输数据
- google-cloud-platform - 在 Google Cloud Run 中容器化应用程序时出现 Docker 错误
- javascript - JS棋盘阅读器Y坐标问题
- python - 与 python 类似的句子 like bash with jq