【发布时间】:2020-05-31 14:39:14
【问题描述】:
我知道标题有点难以理解,但下面的例子应该能阐明我的意思:
假设您有一个包含 2 个重载的方法:
void Method(int i)
{
Console.WriteLine("Method(int) called");
}
void Method(int i, string s)
{
Console.WriteLine("Method(int, string) called");
}
那么你有另一种方法,它采用可变数量的参数:
void MethodOverload(params dynamic[] parameters)
{
Method(parameters); // Call one of the overloading methods depending on the parameter amount and their type
}
上面的方法接受任意数量的任意类型的参数。我想根据传递的参数数量及其类型调用其中一种重载方法。
例如:
void Run()
{
TestFuncOverload(5); // Output: "testFunc(int) called"
TestFuncOverload(5, "some text"); // Output: "testFunc(int, string) called"
TestFuncOverload(5, 5); //Error
}
如何在 C# 中实现这一点?
【问题讨论】:
-
if (parameters.Length == 1 && parameters[0] is int) Method(parameters[0]); if (parameters.Length == 2 && parameters[0] is int && parameters[1] is string) Method(parameters[0], parameters[1]);怎么样,我没有看到其他解决方案。 -
嗯,是的,但这是一个简化的示例。每次我在代码中需要这样的东西时,我不想为所有类型的参数和每个函数的所有重载数量创建几十个 if 语句。
标签: c# variables dynamic parameters overloading