return 取决于条件的值

return a value depending on condition

假设我有以下扩展方法:

public static string sampleMethod(this int num) {
    return "Valid";
}

如果 num > 25 我如何终止 sampleMethod 并显示消息框?

如果我尝试下面的代码,我会在 sampleMethod 上收到一条红色下划线并显示 not all code path returns a value

public static string sampleMethod(this int num) {
    if(num > 25) {
        MessageBox.Show("Integer must not exceed 25 !");
    } else {
        return "Valid String";
    }
}

如果我在 MessageBox.Show 下添加 throw new Exception("...");,一切顺利,但应用程序终止。

如果不满足条件,如何显示 MessageBox 并终止方法?

谢谢。

确保你总是return一个string(因为字符串是你的return值)到你的函数outcome/path的所有可能

public static string sampleMethod(this int num) {
    if(num > 25) {
        MessageBox.Show("Integer must not exceed 25 !");
        return "";
    }

    return "Valid String";
}

您的代码无效,因为

public static string sampleMethod(this int num) {
    if(num > 25) {
        MessageBox.Show("Integer must not exceed 25 !");
        // when it go to this block, it is not returning anything
    } else {
        return "Valid String";
    }
}

假设您有一个包含 25 个索引的字符串数组:

public String[] data = new String[25] { /* declare strings here, e.g. "Lorem Ipsum" */ }

// indexer
public String this [int num]
{
    get
    {
        return data[num];
    }
    set
    {
        data[num] = value;
    }
}

当数组索引超过 25 时,如果您不想 return 任何字符串,则应将方法更改如下:

public static String sampleMethod(this int num) {
    if(num > 25) {
        MessageBox.Show("Integer must not exceed 25 !");
        return String.Empty; // this won't provide any string value
    } else {
        return "Valid String";
    }
}