简体   繁体   English

将 model class 作为泛型类型参数传递

[英]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.我想创建一个可以将通用 model 作为其参数的方法。 Inside GenericMethod, if I wanted to access the property of models, how do I actually configure the method?在 GenericMethod 内部,如果我想访问模型的属性,我该如何实际配置该方法?

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 :我会为此使用一个通用接口,例如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.).接口在这里比类更好,因为您可以实现多个并且它们具有其他优点(例如单元测试、IoC 等)。

inherit ModelA and ModelB from a common parent having the field Name, and make like从具有字段名称的共同父级继承 ModelA 和 ModelB,并制作类似

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.您可以为您的模型创建一个父 class 并将其类型作为参数传递。

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.假设您不需要/不想要Parent class 的任何实例,您可能希望将其设为摘要。

Some links一些链接

to read:读书:

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

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