简体   繁体   English

泛型类型约束,其中类实现抽象类

[英]Generic Type Constraint where class implements an abstract class

I have an Generic Abstract Class with some properties like Id , Name , Status , this class inherits several catalogs. 我有一个具有某些属性的Generic Abstract Class ,例如IdNameStatus ,该类继承了几个目录。 My question is whether it is possible to create a method with a restriction for the catalogs that implement the Abstract Class. 我的问题是,是否有可能为实现Abstract Class的目录创建一个受限制的方法。

I give some examples so that they understand what I want to do: 我举一些例子,以便他们理解我想做什么:

public abstract class AbsCatalog<T>
{
    public T Id { get; set; }
    public string Name { get; set; }
    public bool Status { get; set; }
}

These are the classes that implement the abstract class 这些是实现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; }
}

The method I want to implement is the following: 我要实现的方法如下:

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;
}

I think the only way is to use two generic type parameters here, for example: 我认为唯一的方法是在这里使用两个通用类型参数,例如:

private string GetDescription<T, U>(List<T> list) where T : AbsCatalog<U>
{
    //snip   
}

And then call it like this: 然后这样称呼它:

string AgentsDescription = GetDescription<Agent, string>(Agents);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM