我们可以创建具有相同名称但在类中具有不同数据类型的重载方法

时间:2014-02-06 12:13:04

标签: c#

Class StudentFeeCollection
{
public static bool CheckAdmissionMonth(int AdmissionNo)
 {
 }
public static DataTable CheckAdmissionMonth(int AdmissionNo)
 {
 }
}

这是否可能,请告诉我。

4 个答案:

答案 0 :(得分:1)

您可以使用out parameter

 class StudentFeeCollection
{
public static void CheckAdmissionMonth(int AdmissionNo, out bool result)
{
    ........
}
public static void CheckAdmissionMonth(int AdmissionNo, out DataTable tbl)
{
    .......
}

答案 1 :(得分:0)

不,那是不可能的。您需要确保每个重载的签名都是唯一的。

来自文档:

Changing the return type of a method does not make the method unique as stated 
in the common language runtime specification. You cannot define overloads that 
vary only by return type.

参考: http://msdn.microsoft.com/en-us/library/vstudio/ms229029(v=vs.100).aspx

答案 2 :(得分:0)

这是不可能的。想象一下你是编译器还是运行时 - 你怎么知道代码要求的返回类型?如果您确实需要支持从方法返回多个数据类型,那么使用泛型是最好的选择。也就是说,看看你的具体例子,我建议不要在这里做。有一个返回布尔值或DataTable的方法看起来像是一个非常粗暴的设计。

答案 3 :(得分:0)

您可以通过c#中的参数类型重载,但不能通过返回类型重载。 正如Arshad所说,你可以使用out / ref参数,因为它们是参数而不是返回类型。

此外,你不能通过参数的泛型约束来重载(比如有两个版本,其中一个是结构,另一个是类)。见https://msmvps.com/blogs/jon_skeet/archive/2010/10/28/overloading-and-generic-constraints.aspx

避免返回类型重载的一个原因,来自c ++语言描述:

  

原因是要保持单个运算符或函数调用的分辨率与上下文无关。

注意:在像haskell这样的编程语言中,你可以通过返回类型重载 有关详细信息,请参阅Function overloading by return type?

相关问题