具有可变参数的函数的委托 [英] A delegate for a function with variable parameters

查看:65
本文介绍了具有可变参数的函数的委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种功能

void func(params object[] parameters) { 
    //Function Body
}

它可以接受以下类型的参数

It can accept parameters of the following sort

func(10, "hello", 30.0);
func(10,20);

等。

我想要为上述功能创建 Action 委托。可能吗?如果不是,为什么?

I wanted to create an Action delegate for the above function. Is it possible? If not then why?

推荐答案

您不能使用现有的 Action 具有 params 的代表,但是您可以这样声明自己的代表:

You can't use the existing Action delegates with params, but you can declare your own delegate that way:

public delegate void ParamsAction(params object[] arguments)

然后:

// Note that this doesn't have to have params, but it can do
public void Foo(object[] args)
{
    // Whatever
}

...

ParamsAction action = Foo;
action("a", 10, 20, "b");

当然,您可以创建 Action< object []> 为您现有的方法-但您失去了它的 params 方面,因为在中没有声明动作< T> 。因此,例如:

Of course you can create an Action<object[]> for your existing method - but you lose the params aspect of it, as that's not declared in Action<T>. So for example:

public static void Foo(params object[] x)
{
}

...

Action<object[]> func = Foo;
func("a", 10, 20, "b"); // Invalid
func(new object[] { "a", 10, 20, "b" }); // Valid

因此,如果您要从代码中调用想要使用 params ,您需要一个在声明中包括该类型的委托类型(按照第一部分)。如果您只想创建一个接受 object [] 的委托,则可以创建<$> $ 的 instance 。 object []> 使用签名中具有 params 的方法-实际上,它只是一个修饰符。

So if you're calling the delegate from code which wants to use params, you need a delegate type which includes that in the declaration (as per the first part). If you just want to create a delegate which accepts an object[], then you can create an instance of Action<object[]> using a method which has params in its signature - it's just a modifier, effectively.

这篇关于具有可变参数的函数的委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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