开发者

Pass class as argument

I have an api method I need to call. It has 10 parameters. I have attempted to make a class that holds all the information the method requires. Can I then simply pass the object into the method?

myAPIMethod(myClass);

Does it work that easily开发者_开发问答?


No, it doesn't work that way. If a method has 10 parameters, you will have to pass 10 arguments to it.

If you have control of the API, you can refactor it to accept a single object instead.

If you don't have control of the API, you can write a method along the lines of

public void CallAPI(MyClass args)
{
   myAPIMethod(args.Arg1, args.Arg2); // whatever args are needed for the method
}

Then your code can use your class and this method to invoke the API. It could be a cleaner approach than invoking the API method directly with 10 arguments in multiple places in your application. But, this depends on what the method is and how you're using it.


Short answer: no, you can't do that.

This is not quite what you were looking for, but in some languages (e.g. Python) you can create something called a partial application (sometimes incorrectly called currying). This allows you to create a new function that calls another function, but with some of the params pre-specified.


You create an instance of the class, called an object, and pass the object - thus "object oriented programming"

If your method requires 10 parameters though, you must pass 10 parameters. You can't just pass an object that contains 10 parameters unless you rewrite your method.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜