简体   繁体   English

如何从函数中调用重载方法并在C#中传递不同的参数类型

[英]How to call overload method from a function and pass different argument types in c#

I have two overloaded methods as below: 我有两个重载的方法,如下所示:

Render(PDFTable table)
Render(PDFText text)

I have to call these methods from another method inside a for..each loop and pass the parameters as below: 我必须从for..each循环内的另一个方法调用这些方法,并按如下所示传递参数:

foreach (var item in sectionPDF.sectionElements)
{
    if (item.GetType().Equals(typeof(PDFTable)))
    {
        Render((PDFTable)item);
    }
    else if (item.GetType().Equals(typeof(PDFText)))
    {
        Render((PDFText)item);
    }
}

I would like to know, if there is any way to remove the if..else statements and dynamically resolve the type? 我想知道,是否可以删除if..else语句并动态解析类型? Thanks in advance. 提前致谢。

No, there isn't. 不,没有。 C# doesn't support virtual dispatch based on argument type. C#不支持基于参数类型的虚拟调度。 Overload resolution is a purely compile-time matter. 重载解析是一个纯粹的编译时问题。 Hence you have to make the decision yourself, either the way you are doing it now, by using some form of a decision table, using a provider class that makes the decision, whatever else fits your software design. 因此,无论采用哪种方式,您都必须自己做出决策,方法是使用某种形式的决策表,使用提供者类来做出决策,而其他任何适合您的软件设计的决策也应如此。

You can use dynamic . 您可以使用dynamic First declare a method like this: 首先声明这样的方法:

void RenderDispatch(dynamic item)
{
    Render(item);
}

Render((PDFTable)
Render((PDFText)

Then in the foreach : 然后在foreach

foreach (var item in sectionPDF.sectionElements)
{
    RenderDispatch(item);
}

The runtime take care to call the correct override. 运行时注意调用正确的覆盖。

Beware that dynamic incurs in performance issue. 注意 dynamic会导致性能问题。

You can make your "Render" method generic: 您可以使“ Render”方法通用:

void Render<T> (T item)
{
    //your stuff here
}

then: 然后:

foreach (var item in sectionPDF.sectionElements)
{
    Render(item);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM