简体   繁体   中英

Passing model class as a generic type parameter

I have a skeleton code like this. I want to create a method that can take a generic model as its argument. Inside GenericMethod, if I wanted to access the property of models, how do I actually configure the method?

public class ModelA
{
    public string Name { get; set;}
    public int Property1 { get; set; }
}

public class ModelB
{
    public string Name { get; set;}
    public int Property2 { get; set; }
}

public class MainClass
{
    public async Task<int> ProcessA()
    {
        await GenericMethod(ModelA modelA);
    }

    public async Task<int> ProcessB()
    {
        await GenericMethod(ModelB modelB);
    }

    public async Task<int> GenericMethod<T>(T model) where T : something?
    {
        // Get model name here like this
         model.Name
    }
}

Any help would be highly appreciated. Thank you.

I would use a common interface for this, for example IHaveName :

public interface IHaveName
{
    string Name { get;set; }
}


public class ModelA: IHaveName
{
    public string Name { get; set; }
}

public class ModelB: IHaveName
{
    public string Name { get; set; }
}

Now you can make a constraint on it:

public async Task<int> GenericMethod<T>(T model) where T : IHaveName
{
    // Get model name here like this
     model.Name
}

Interfaces are better than classes here since you can implement multiple and they have other advantages(for example unit tests, IoC etc.).

inherit ModelA and ModelB from a common parent having the field Name, and make like

public async Task<int> GenericMethod<T>(T model) where T : IModelParent

You can make a parent class for your models and pass its type as an argument.

abstract class ModelParent
{
    public virtual string Name { get; set; }
}

public class ModelA : ModelParent
{
    public override string Name { get => base.Name; set => base.Name = value; }
}

public class ModelB : ModelParent
{
    public override string Name { get => base.Name; set => base.Name = value; }
}

public class MainClass
{
    public async Task<int> ProcessA()
    {
        await GenericMethod(ModelA modelA);
    }

    public async Task<int> ProcessB()
    {
        await GenericMethod(ModelB modelB);
    }

    public async Task<int> GenericMethod<T>(T model) where T : ModelParent
    {
        // Get model name here like this
        model.Name
    }
}

Assuming that you do not need/want any instances of Parent class, you might want to make it an abstract.

Some links

to read:

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