开发者

Is it possible to make an abstract method's parameter list have overridable length and types?

开发者 https://www.devze.com 2023-02-07 05:01 出处:网络
Is it possible to create a base class like the following: public abstract class baseClass { public abstract void SetParameters(/*want this to be adjustable*/);

Is it possible to create a base class like the following:

 public abstract class baseClass
{
     public abstract void SetParameters(/*want this to be adjustable*/);
}

so that classes that override it can define the parameters required? In other words, I want to force the method to be overridden, but leave it up to the overriding class what is required here - so one might be

 public class derivedClass1 : baseClass
{
     public override void SetParameters(Point a, int b);
}

whereas another could be

 public class derivedClass2 : baseClass
{
    开发者_运维技巧 public override void SetParameters(List<Line> a, Point b, Point c, bool e);
}

?

Thanks for any help you can give


Absolutely not - that would break half the point of having the abstract method in the first place - no-one would be able to call it, because they wouldn't know which method signature had actually been written. The whole point of an abstract class is that a client can have a reference of type BaseClass without caring about what the type of the actual implementation is.

If the base class is able to predict in advance which types might be involved, one possibility to make life easier for the caller is to have the most general signature (typically the one with the most parameters) abstract, and make various overloads which call that general one providing defaults for the parameters that the client hasn't specified.


It can be done IF the parameters were all set to the same type and in the same number i guess (not sure if you can use params T[], but if its possible, then you can adjust it too). You can achieve by using Generics, like @simonalexander2005 said

public abstract class baseClass<T> where T : class
{
     public abstract T SetParameters(params T[] parameters);
}

its up to you to decide how many parameters the derived class will use. But, im not sure if its a good practice...


No, this isn't possible. An overriding method needs to match the parameters exactly—it's the same as implementing an interface. You may be interested in the double-dispatch pattern.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号