如何定义可以接受不同参数序列的方法? [英] How do I define a method which can accept different sequences of arguments?

查看:29
本文介绍了如何定义可以接受不同参数序列的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C#、Python 和/或 VB.NET 中,如何编写可以接受不同参数序列的类的方法?作为指示,当在 Visual Studio 中按 shift+shift+space 时,可以访问参数序列的多种选择.

In C#, Python and/or VB.NET, how can I write a method of a class that can accept different sequences of arguments? As an indication, the multiple choices of arguments sequence would be accessible when pressing shift+shift+space in Visual Studio.

推荐答案

我尝试在方法重载和可变参数编号上更加明确一些.你可以在同一个 interfaceclassstruct 中拥有不同的同名方法,只要它们有不同数量的参数或参数C# 和 VB 中的不同类型(或两者).C# 示例:

I try to be bit more explicit on method overloading and variable parameter numbers. You can have different methods with the same name in the same interface, class or struct as long as they have a different number of parameters or parameters of different types (or both) in C# and VB. C# example:

public int Foo(string s)       // OK, first method
public int Foo(double d)       // OK, different type
public void Foo(double x)      // Error, same parameter type, return
                               // type and parameter name do not matter.
public int Foo(string s, DateTime d)   // OK, diffent number of parameters.

另外,最后一个参数可以是一个数组,代表不同数量的参数.它必须用 params 关键字 (C#) 或 ParamArray 关键字 (VB) 引入.

In addition, the last parameter can be an array, which represents a varying number of parameters. It must be introduced with the params keyword (C#) or the ParamArray keyword (VB).

C#

public int Foo(string s, params int[] n)

VB

Function Foo(ByVal s As String, ByVal ParamArray n As Integer()) As Integer 

你可以这样称呼它,C#

You can call it like this, C#

int i = Foo("Hello");   
int i = Foo("Hello", 5);   
int i = Foo("Hello", 5, 7);   
int i = Foo("Hello", 5, 7, 13);   
int i = Foo("Hello", new int[] { 2, 4, 6 });   

这篇关于如何定义可以接受不同参数序列的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆