我有一个 Generic Abstract Class
具有一些属性,例如 Id
、Name
、Status
,此类继承几个目录。
我的问题是是否可以创建一个对实现抽象类的目录有限制的方法。
我举一些例子让他们明白我想做什么:
public abstract class AbsCatalog<T>
{
public T Id { get; set; }
public string Name { get; set; }
public bool Status { get; set; }
}
这些是实现抽象类
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);
关于c# - 类实现抽象类的通用类型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45845174/