gpt4 book ai didi

c# - 如何在运行时调用正确的重载函数?

转载 作者:太空宇宙 更新时间:2023-11-03 22:28:15 24 4
gpt4 key购买 nike

如何根据对象的实际类型在给定对象引用的情况下调用正确的重载函数。例如……

class Test
{
object o1 = new object();
object o2 = new string("ABCD");
MyToString(o1);
MyToString(o2);//I want this to call the second overloaded function


void MyToString(object o)
{
Console.WriteLine("MyToString(object) called.");
}

void MyToString(string str)
{
Console.WriteLine("MyToString(string) called.");
}
}

我的意思是有比以下更好的选择吗?

if(typeof(o) == typeof(string))
{
MyToString((string)o);
}
else
{
MyToString(o);
}

这是否可以使用反射来完成?

最佳答案

好吧,我一点击帖子我就记起这确实可以使用反射来完成...

var methInfo = typeof(Test).GetMethod("MyToString", new Type[] {o.GetType()});
methInfo.Invoke(this, new object[] {o});

关于c# - 如何在运行时调用正确的重载函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/330832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com