[英]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.