[英]Creating abstract class with 'where' constraint that also implements interfaces
[英]Generic Type Constraint where class implements an abstract class
我有一个具有某些属性的Generic Abstract Class
,例如Id
, Name
, Status
,该类继承了几个目录。 我的问题是,是否有可能为实现Abstract Class的目录创建一个受限制的方法。
我举一些例子,以便他们理解我想做什么:
public abstract class AbsCatalog<T>
{
public T Id { get; set; }
public string Name { get; set; }
public bool Status { get; set; }
}
这些是实现abstract class
public class Agent : AbsCatalog<string>
{
public string Office { get; set; }
public Estado Estado { get; set; }
}
public class Models : AbsCatalog<int>
{
public int Year { get; set; }
public string Description { get; set; }
}
我要实现的方法如下:
List<Agent> Agents = service.GetAgents();
string AgentsDescription = GetDescription<Agent>(Agents);
List<Model> Models = service.GetModels();
string ModelsDescription = GetDescription<Model>(Models);
private string GetDescription<T>(List<T> list) where T : AbsCatalog<T>
{
string description = string.Empty;
if (list.Exists(x => x.Id.ToString() == "0"))
description = "";
else
description = string.Join(", ", list.Where(x => x.Status).Select(x => x.Name).ToArray());
return description;
}
我认为唯一的方法是在这里使用两个通用类型参数,例如:
private string GetDescription<T, U>(List<T> list) where T : AbsCatalog<U>
{
//snip
}
然后这样称呼它:
string AgentsDescription = GetDescription<Agent, string>(Agents);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.