是否必须设置Invoke';s参数始终为Object()
本文关键字:参数 Object 设置 Invoke 是否 | 更新日期: 2023-09-27 18:22:30
.Invoke
方法需要将args参数设置为new object[]
,这是必要的吗?我的意思是,我可以将其设置为new string[]
,还是直接设置为不使用数组?例如,我可以这样使用它吗:
this.Invoke(delegate, "Some text");
或者像这样:
this.Invoke(delegate, new string[] { "Some text"} );
还是必须将其设置为new object[]
?
this.Invoke(delegate, new object[] { "Some text"} );
如果这听起来很蹩脚,我很抱歉,但我检查的每一个代码都使用Object数组,甚至是MSDN的,而据我所知,将其用作String会更快,尽管每个人都使用Object肯定是有原因的,这就是我问的原因。感谢您的提前回答。
this.Invoke(delegate, "Some text");
和this.Invoke(delegate, new object[] { "Some text"} );
会导致传入new object[] { "Some text"}
。
但是,执行this.Invoke(delegate, new string[] { "Some text"} );
将导致对象被包装,并且您将传入new object[] { new string[] { "Some text" } }
。
更新:我刚刚测试了这个,我似乎错了,我100%确信行为是不同的。当使用string[]
时,所有三种调用方式都会产生相同的结果。我所描述的行为只发生在类型不可隐式转换的情况下,例如使用int[]
时。
下面是一个显示行为的示例程序
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Testing string[]");
var test = new string[1] {"example"};
Example(test);
Console.WriteLine();
Console.WriteLine("Testing int[]");
var test2 = new int[1] {0};
Example(test2);
}
public static void Example(params object[] test)
{
Console.WriteLine("Array Type: {0}", test.GetType());
Console.WriteLine("test[0] Type: {0}", test[0].GetType());
}
}
/* Outputs:
Testing string[]
Array Type: System.String[]
test[0] Type: System.String
Testing int[]
Array Type: System.Object[]
test[0] Type: System.Int32[]
*/