简体   繁体   中英

Force a class to implement a method without restricting the parameters in C#

I have an interface that contain the method void DoCommand(); . now I'll force all the child classes to inherit the base class method DoCommand() . but I need each class to define a different parameter for this method to serve the page with the proper parameters.

How can I do that ? Is it even possible !

NB: I'm building an ASP.NET web application and the page that will implement the method already inherits from the page base class, so I think Interface is my only option. as only one base class is allowed in inheritance of classes.


Edit

I hope illustrating what I need this for could let you help me to come up with a better design and stick to the rich concepts like OOP.

I have 19 pages, each page will need a method to collect data from the input controls in this page and put it in an object (19 pages .. 19 types of objects)

so I need Collect(); to be forced, then each page will take as a parameter the proper type of object .. does it make more sense ?

btw if you think that my design is totally wrong, a whole new design patterns are welcome (Y)

It's not possible. The closest you can come is to have your method be generic and take a single generic argument:

protected abstract void DoCommand<T>(T parameter);

Short of that you'll have to use a property bag of some sort (like NameValueCollection ).

The best I can think of is:

interface IBlaBla
{
     void DoCommand(params object[] parameters);
}

and then each class receives the parameters as a sequence of objects.

Otherwise, you'll just have to define a brand new method for each class.

The interface will need to have all the functions (with different parameter). There is no reason to have an interface otherwise

Edit: You might want something like this (using generics)

public interface ICollect<T>
{
    void Collect(T obj);
}

public class Car : ICollect<Car>
{
    public void Collect(Car obj)
    {
    //Do stuff
    }
}

It does not make sense. This violates the whole idea of polymorphism: the base class(or interface) has a method and child classes provide their own implementation. If you didn't mean to use a generic parameter, then the methods of your child classes are different from the base class, they just appear to have the same name. So you can't force your child classes to implement 'some routine with a given name but arbitrary parameters'.

No, that's impossible. However, you can try this:

 void DoCommand(params object[] args); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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