可以用不同的返回类型进行功能过载......? [英] Can function overload with different return type...?
本文介绍了可以用不同的返回类型进行功能过载......?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好我是C#& amp;的初学者.NET。
在下面的代码中,CreateCountry函数声明为int,它的返回类型也是int(这部分我得到了它)
但我对int函数中重载的字符串变量感到困惑,在这段代码中也没有将给定的字符串转换为int值。
请指导我。谢谢(参考:CRUD项目)
Hi I am a beginner in C# & .NET.
In the following code CreateCountry function declared as int and its return type is also int (this part I got it)
But I am confused about the overloaded string variable in int function, also nowhere in this piece of code the given string is converted to int value.
Please guide me. Thank you (Reference:CRUD project)
public int CreateCountry(string countryName)
{
if (string.IsNullOrEmpty(countryName))
{
return -1;
}
else
{
DALCountry dalCountry = new DALCountry();
return dalCountry.CreateCountry(countryName);
}
}
推荐答案
检查国家/地区参数并抛出异常是更好的设计不对。调用函数将有一个try / catch块来处理错误。
It would be better design to check the country argument and throw an exception if it's not right. The calling function would have a try/catch block to handle the error.
public DALCountry CreateCountry(string countryName)
{
if (String.IsNullOrEmpty(countryName))
throw new ArgumentException("countryName");
DALCountry dalCountry = new DALCountry();
return dalCountry.CreateCountry(countryName);
}
你的问题没有多大意义。
您是否询问如何使用具有相同参数类型的副本重载方法,在您的情况下是一个字符串,并且只有返回类型不同?您是否询问方法如何返回整数或DALCountry类型?
这很容易。你不能。您必须更好地规划代码。方法只能返回单个类型。它不能返回多种类型。解决方案#1是最好的解决方案,因为DALCountry类可以保存比单个整数更有意义的信息。
Your question doesn't make a lot of sense.
Are you asking how to overload a method with a copy that takes the same parameter type, a string in your case, and differs only by the return type? Are you asking how a method can return either an integer OR a DALCountry type?
It's easy. You can't. You must plan your code better. A method can only ever return a single type. It cannot return multiple types. Solution #1 is the best solution as a DALCountry class can hold much more meaningful information than a single integer can ever hold.
'CreateCountry不是声明为int。它返回一个'int,它需要一个'字符串参数。
'DALCountry类中的'CreateCountry方法必须与您在此处显示的'CreateCountry方法不同,或者:该方法会递归调用自身,直到出现堆栈溢出错误。
此处没有重载字符串变量。
'CreateCountry is not "declared as int." It returns an 'int, and it takes a 'string parameter.
The 'CreateCountry method in the 'DALCountry class must be different from the 'CreateCountry method you show here, or: the method would call itself recursively until there was a stack overflow error.
There is no "overloaded string variable" here.
这篇关于可以用不同的返回类型进行功能过载......?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文