关于C#的一个返回值问题

图片说明

我想当a和b的长度为0时,不返回正确或错误,怎么改代码呀

首先,你的方法(函数)是必然要返回一个boolean值,所以你想当a和b的长度为0时,不返回正确或错误的话,那你想返回什么?

如果单纯不想在a和b的长度为0时,不返回正确或错误的话,不输入空串,不做为0的判断就行了

如果要所有情况都判断一下的话,参考如下:

pulic int daxiao(string a , string b)
{
    if (a.Length > b.Length) 
    {
         return 0;
    }
    else if (...)
    {
        return 1;
    }
    else if (...)
    {
        for (...)
        {
            if (...) { return 1; }
            if (...) { return 0; }
        }
    }
    else if (a长度等于0 && b长度等于0)
    {
        return 2;
    }
}

上面的...表示和你的一样,增加一个对长度为0的判断,如果为0,就返回2

返回1为true , 0为false , 2表示长度为0

最后用来接受这个返回数据的地方改一下接收方式,改一下判断就是了

如果没什么问题 ,请采纳,谢谢。

11:53分开始更新

关于返回值到while的参考样式

int flag = 0;
flag = daxiao(s1 , s2);
while (flag == 1)
{
    //当flag为1(true)的时候 , 执行方法体 ,如果返回0和2,就不执行了
}

如果你要做更详细的判断

就可以用if语句来解决

参考如下

int flag = 0;
flag = daxiao(s1 , s2);

if (flag == 0)
{
    //0为false,判断出s1小于s2
    ...
}
else if (flag == 1)
{
    //1为true,判断出s1大于s2
    ...
}
else if (flag == 2)
{
    //2为字符串长度为0
    ...
}

以上思路仅供参考,实际情况不同也会有不同的改变

之前告诉你了,如果你认为代码会执行到最后没有返回值是一种错误,最好的办法是用throw兜底:
看下面的例子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Q715035
{
    class Program
    {
        static public bool daxiao(string s1, string s2)
        {
            if (s1.Length == 0)
                throw new ArgumentException("s1为0");
            if (s2.Length == 0)
                throw new ArgumentException("s2为0");
            if (s1.Length != s2.Length) return s1.Length > s2.Length; //前面几行可以简写成1行
            int i = 0;
            for (i = 0; i < s1.Length; i++)
                if (s1[i] != s2[i])
                    return s1[i] > s2[i];
            throw new ArgumentException("结果相等");
        }

        static void Main(string[] args)
        {
            string s1 = "123";
            string s2 = "123";
            try
            {
                Console.WriteLine(daxiao(s1, s2));
            }
            catch
            {
                Console.WriteLine("相同或者字符串为空");
            }
        }
    }
}

额,程序是死的。人是活的
返回值bool改成返回数字或者字符串
其中bool值只有true跟false满足不了当前的判断,当前需要三个参数分别去代表
当A>B return 0;
当B>A return 1;
当所有条件不成立时 return 2;
这时返回的0代表true,返回的1代表false,返回的2代表相同且为0的时候