实现一个抽象方法时,更改参数类型 [英] Change parameter type when implementing an abstract method

查看:147
本文介绍了实现一个抽象方法时,更改参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有某种方式在一个抽象方法来定义一个抽象类型作为参数,并且当该方法在派生类被实现,则改变了该方法的类型来接受派生类型?

Is there some way to define an abstract type as a parameter in an abstract method, and when that method is implemented in a derived class, you change the type of the method to accept a derived type?

代码:

public abstract class ProductBase
{
}

public class SomeProduct
    : ProductBase
{

}

public abstract class A
{
    protected abstract void addProduct(ProductBase p);
}

// This works
public class B : A
{        
    protected override void addProduct(ProductBase p)
    {
        // Do some work
    }
}

// This is what I'd like to do
public class C : A
{
    // Compiler error here because I have accepted a SomeProduct and not a ProductBase
    protected override void addProduct(SomeProduct p)
    {
        // Do some work on the specialisation - I can use the SomeProduct directly
    }
}

在我的头上,这让某种意义。指示有一个抽象类是其中的派生类必须实现的方法,但他们可以改变传递作为参数的对象的类型,只要它是从同一继承链...

In my head, it makes some kind of sense. An abstract class indicating there is a method which derived classes must implement, but they can change the type of object passed in as a parameter, so long as it is from the same inheritance chain...

我已经落得这样做,是从抽象类中删除的抽象方法 addProduct命令,而是只实现它在派生类中,无论如何,但有那么没有合同的其他类在未来,他们必须创建自己的实施 addProduct命令的。而且这不会的感觉不对

What I have ended up doing, is to remove the abstract method AddProduct from the abstract class, and instead just implementing it in the derived class anyway, but there's then no contract for other classes in the future that they must create their own implementation of AddProduct. And it doesn't feel right.

我希望这是有道理的。道歉,如果这是一个重复的问题,但我无法找到通过搜索任何东西。

I hope this makes sense. Apologies if this is a duplicate question but I couldn't find anything by searching.

谢谢,结果
bgs264

Thanks,
bgs264

推荐答案

您可以让你的 A 类通用的,在你的 addProduct命令方法:

You can make your A class to generic and use the generic argument in your addProduct method:

public abstract class A<TProduct> where TProduct : ProductBase 
{
    protected abstract void addProduct(TProduct p);
}

public class B : A<ProductBase>
{        
    protected override void addProduct(ProductBase p)
    {
    }
}

public class C : A<SomeProduct>
{
    protected override void addProduct(SomeProduct p)
    {
    }
}

这篇关于实现一个抽象方法时,更改参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆