重载方法调用重载方法 [英] Overloaded method calling overloaded method

查看:142
本文介绍了重载方法调用重载方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我写的是调用另一个里面重载方法的方法。我想只写一个外方法中,由于参数到外方法被传递到内之一。有没有办法做到这一点?

I have a method that I'm writing that is calling another overloaded method inside it. I'd like to only write one outer method, since the parameter to the outer method is being passed to the inner one. Is there a way to do this?

我试着使用泛型,但我不知道有足够的了解这个所以它是不工作:

I tried using generics, but I don't know enough about this so it isn't working:

public void OuterMethod<T>(T parameter)
{
    InnerMethod(parameter); // InnerMethod accepts an int or a string
}

我知道我可以做到这一点:

I know that I can do this:

public void OuterMethod(string parameter)
{
    InnerMethod(parameter);
}

public void OuterMethod(int parameter)
{
    InnerMethod(parameter);
}

但我宁愿这样做的正确的方式,而不是复制/粘贴code。什么是实现这一目标的最好方法是什么?

But I'd rather do this the right way instead of copying/pasting code. What's the best way to accomplish this?

推荐答案

您可以在C ++中做到这一点,但不是在C#(除非内部方法也可以通用的,而不是过载)。

You can do this in C++ but not in C# (unless the inner method can also be generic instead of overloaded).


或者(如果你不采取不的回答),你可以做一个运行时开关类型,例如像...

Alternatively (if you won't take 'no' for an answer), you can do a run-time switch on type, like for example ...

public void OuterMethod(object parameter)
{
    if (parameter is int)
        InnerMethod((int)parameter);
    else if (parameter is string)
        InnerMethod((string)parameter);
    else
        throw new SomeKindOfException();
}

...但很明显这是一个运行时,不编译时检查。

... but obviously this is a run-time, not a compile-time check.

但我宁愿这样做的正确的方式,而不是复制/粘贴code。

But I'd rather do this the right way instead of copying/pasting code.

您也可以编写软件来写你的外部方法(例如,使用系统。codeDOM类),而不是用手工写他们,但是这可能是更多的麻烦比它的价值。

You can also write software to write your outer methods (e.g. using System.CodeDom classes) instead of writing them by hand, but this is probably more trouble than it's worth.

这篇关于重载方法调用重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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