简体   繁体   English

继承和通用类型

[英]Inheritance and generic type

I have a generic model that implements a static method. 我有一个实现静态方法的通用模型。 Ideally I would like to avoid having to implement the method in the class that inherits the generic class. 理想情况下,我希望避免在继承通用类的类中实现该方法。 But I can't see how I can avoid setting the type. 但是我看不到如何避免设置类型。

It would be cool if I could get the type directly in the generic model... 如果我可以直接在通用模型中获取类型,那将很酷...

Any suggestions? 有什么建议么?

abstract public class GenericFactory
    {
        public async Task<T> FindByUuid<T>(Guid uuid) where T:GenericModel, new()
        {
            return await rest.HttpGet<T>($"https://.../{uuid.ToString()}");
        }
    }

public class Contracts : GenericFactory
    {
        public async Task<Contract> FindByUuid(Guid uuid)
        {
            return await base.FindByUuid<Contract>(uuid);
        }
    }

EDIT: Sorry, my example was wrong. 编辑:对不起,我的例子是错误的。 I removed and changed some things around to make my point clear. 我删除并更改了一些内容以使观点更清楚。 Instead I did the opposite. 相反,我做了相反的事情。 I've edited the code example to reflect this. 我已经编辑了代码示例以反映这一点。

I assume you want your derived class Contract to only allow instances of Contract within your FindByUuid -method. 我假设您希望派生类Contract仅在FindByUuid -method中允许Contract实例。 Doing so won´t need to override the base-method, you just have to set the generic type-parameter to your class instead of the method itself: 这样做不需要覆盖基本方法,您只需要为您的类而不是方法本身设置通用类型参数即可:

public class GenericFactory<T> where T : GenericModel, new()
{
    public async Task<T> FindByUuid<T>(Guid uuid) 
    {
        return await rest.HttpGet<T>($"https://.../{uuid.ToString()}");
    }
}

public class Contracts : GenericFactory<Contract> { ... }

Now all instances of Contracts have the method FindByUuid that only accepts instances of Contract . 现在,所有Contracts实例都具有FindByUuid方法,该方法仅接受Contract实例。 No need for overriding - in your case it´s actually hiding as there allready exists a member with that name in the base-class. 不需要覆盖-在您的情况下,它实际上是隐藏的,因为在基类中已经存在一个具有该名称的成员。

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

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