简体   繁体   中英

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. My question is whether it is possible to create a method with a restriction for the catalogs that implement the 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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