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

女生的网名这么多〃 提交于 2019-12-08 14:34:11

问题


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 !

N.B: 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)


回答1:


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
    }
}



回答2:


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).




回答3:


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.




回答4:


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'.




回答5:


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

void DoCommand(params object[] args);



来源:https://stackoverflow.com/questions/5693246/force-a-class-to-implement-a-method-without-restricting-the-parameters-in-c-shar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!