[英]Two class inheriting one abstract class
How do I define the abstract method if class Example1 and class Example 2 have subscribe method that pass in different parameter? 如果类Example1和类Example 2具有通过不同参数传递的订阅方法,该如何定义抽象方法?
abstract class Test
{
public int _a;
public abstract void Subscribe();
}
class Example1 : Test
{
public override void Subscribe(int x,int y,int z)
{
}
}
class Example2 : Test
{
public override void Subscribe(string a, bool b)
{
}
}
Easy. 简单。 Just take the
Subscribe
method out of Test
只需将
Subscribe
方法从Test
删除
abstract class Test
{
public int _a;
}
Those subscribe methods are different methods. 这些订阅方法是不同的方法。 You need to think of them in the same way as you would think of methods with different names, even if they serve a similar purpose.
即使它们具有相似的目的,也需要以与使用不同名称的方法相同的方式来考虑它们。
If they're unique to their derived class, than there's no reason why you need them in the base method in the first place. 如果它们对它们的派生类是唯一的,那么就没有理由首先在基本方法中需要它们。
If you need to determine which Subscribe
to call on your Test
at runtime, than you can use is
如果您需要确定在运行时在
Test
上调用哪个Subscribe
,那么可以使用的方法is
if(abc is Example1)
{
((Example1)abc).Subscribe(a, b, c);
}
If your goal is to ensure merely that the derived classes have a Subscribe
method, and that it can take some arbitrary number of arguments, you can use this: 如果您的目标是仅确保派生类具有
Subscribe
方法,并且可以采用任意数量的参数,则可以使用以下方法:
abstract class Test {
public abstract void Subscribe(params object[] args);
}
You can then implement the Subscribe
method in your derived classes, but you must use the params
signature, which makes no compile time guarantee you'll be getting arguments of the correct type or quantity: 然后,您可以在派生类中实现
Subscribe
方法,但是必须使用params
签名,这不能保证您将获得正确类型或数量的参数的编译时间:
class Example1 : Test
{
public override void Subscribe(params object[] abcd)
{
int x = 0;
int y = 0;
int z = 0;
if (abcd[0] is int)
x = (int) abcd[0];
else
// Complain about this
throw new ArgumentException("The first argument is not an integer");
// Check for other parameters
// ...
Example1Subscribe(x, y, z);
}
public void Example1Subscribe(int x, int y, int z)
{
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.