如何在类中使用两个具有相同签名的方法。 [英] how to have two methods with same signature in a class.

查看:88
本文介绍了如何在类中使用两个具有相同签名的方法。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以建议我除方法覆盖之外的任何方法



例子



方法1:





public int search(int id)

{

搜索数据库1

}



方法2:





public int search(int id)

{

在数据库中搜索2

}

Can some one please suggest me any approach other than method overriding

Example

Method1:


public int search (int id)
{
search in data base1
}

Method 2:


public int search (int id)
{
search in data base2
}

推荐答案

嗯,您可以使用不同的名称:

Well, you could use different names:
public int searchDB1 (int id)
{
search in data base1
}

public int searchDB2 (int id)
{
search in data base2
}



或者您可以使用一种方法,并将数据库传递给它:


Or you could have one method, and pass the database to it:

public int search (int id, SqlConnection con)
{
search in data base
}



这实际上取决于你要做什么,为什么。

例如,可能值得将适当的Search方法作为委托参数传递给调用方法:


It really depends on what you are trying to do, and why.
For example, it might be worth passing the appropriate Search method as a delegate parameter to the calling method:

public void DoSomethingIncludingSearch(Func<int> search)
{
    ...    
    search(userId);
    ... 
}

然后用适当的方法调用它:

And then call it with the appropriate method:

public void DoSomething()
{
    ...
    DoSomethingIncludingSearch(searchDB1);
    ...
    DoSomethingIncludingSearch(searchDB2);
}


没有方法覆盖之类的东西。你所谈论的内容与覆盖无关,这是OOP的核心,只有虚拟方法和继承才有可能。



这就像这一样简单:只要编译器有办法确定调用代码应该调用什么,就允许方法具有不同的名称。在你的情况下,这是完全不可能的。如果您的同名方法具有不同的签名,那么这是可能的。即便如此,它可能是一个问题,签名是相似的。例如,一个参数可以与另一个参数分配兼容。只需将自己置于编译器的位置并尝试思考:在调用时选择其中一种方法有多明显?



这通常称为方法重载 但我不知道更多令人遗憾和令人困惑的说法:神经语言程序设计的一些编程方法, 3。术语方法



-SA
There is no such thing as "method overriding". What you are talking about have nothing with "overriding", which is the heart of OOP and is only possible with virtual methods and inheritance.

This is as simple as this: methods are allowed to have different names as soon as the compiler has a way to determine what exactly should be called by the calling code. In your case, this is totally impossible. It would be possible if your methods with the same name had different signatures. Even then, it could be a problem, is the signatures are similar. For example, one parameter could be assignment-compatible with another. Just place yourself in the place of the compiler and try to think: how obvious the choice of one of the method at the call?

This is usually called "method overloading", but I don't know more unfortunate and confusing term that that: Some Programming Approaches to "Neuro-Linguistic Programming", 3. Terminological Methods.

—SA


这篇关于如何在类中使用两个具有相同签名的方法。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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