简体   繁体   English

用泛型覆盖抽象方法

[英]Overriding abstract method with generics

I have an abstract base class that is defined like this: 我有一个定义如下的抽象基类:

public abstract class MyBaseClass<T>

The class contains a definition for the method Get: 该类包含方法Get的定义:

protected abstract MyBaseClass<T> Get(T id);

I create MyClass using MyBaseClass: 我使用MyBaseClass创建MyClass:

public class MyClass : MyBaseClass<string>

Now I have to implement Get , but don't know how to define it: 现在我必须实现Get ,但是不知道如何定义它:

public override MyClass Get(object id)

or 要么

public override MyClass Get(string id)

In both cases I will have to mention string as T and I would like to avoid it. 在这两种情况下,我都不得不将string提到为T ,我想避免使用它。

What is the correct way to override Get ? 重写Get的正确方法是什么?

Thank You. 谢谢。

When you stated the interface you were implementing you specified the generic argument as string when you wrote ( : MyBaseClass<string> ), as such the only way for you to implement the Get method is to use string in place of all values for T . 声明要实现的接口时,您在编写( : MyBaseClass<string> )时将通用参数指定为string ,因此,实现Get方法的唯一方法是使用string代替T的所有值。 If you want users of your class to be able to use other types then you need to make the implementing class generic as well: 如果希望您的类的用户能够使用其他类型,则还需要使实现类通用:

public class MyClass<T> : MyBaseClass<T>
{
    protected override MyBaseClass<T> Get(T id)
    {
        throw new NotImplementedException();
    }
}
public abstract class MyBaseClass<T>
{
    protected abstract MyBaseClass<T> Get(T id);
}

public class MyClass : MyBaseClass<string>
{
    protected override MyBaseClass<string> Get(string id)
    {
        return FindById(id);//implement your logic
    }
}

Implement abstaract class as follows: 实现abstaract类,如下所示:

public abstract class  MyBaseClass<T>
{
    protected abstract MyBaseClass<T> Get(T id);

    protected abstract MyBaseClass<T> Get(string id);
}

And the extending class: 和扩展类:

class Class1 : MyBaseClass<Object>
{
    protected override MyBaseClass<object> Get(object id)
    {
        return (MyBaseClass<object>) id;
    }

    protected override MyBaseClass<object> Get(string id)
    {
        return FindMyBaseClass(id)
    }
}

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

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