繁体   English   中英

根据条件返回值

[英]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";
    }
}

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

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

谢谢。

确保始终向函数的所有可能结果/路径返回一个string (因为字符串是您的返回值)

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时返回任何字符串,则应按以下方式更改方法:

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";
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM