Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 字段中没有@会导致它崩溃_C# - Fatal编程技术网

C# 字段中没有@会导致它崩溃

C# 字段中没有@会导致它崩溃,c#,C#,我在电子邮件验证方面遇到了一些问题 我有两个变量,email和emailTrim,email存储用户输入的电子邮件地址emailTrim,由以下代码组成: string emailTrim = email.Substring(0, email.LastIndexOf("@")); 这将接受email变量并删除@符号后的所有内容。 这正是我想要它做的,然而,这是错误“ArgumentOutOfRangeException未处理”的副作用 有人能帮我一个忙吗?要么用另一种方法删除@符号后面的所有内

我在电子邮件验证方面遇到了一些问题

我有两个变量,email和emailTrim,email存储用户输入的电子邮件地址emailTrim,由以下代码组成:

string emailTrim = email.Substring(0, email.LastIndexOf("@"));
这将接受email变量并删除@符号后的所有内容。 这正是我想要它做的,然而,这是错误“ArgumentOutOfRangeException未处理”的副作用

有人能帮我一个忙吗?要么用另一种方法删除@符号后面的所有内容,要么用另一种方法“处理”抛出的异常


提前感谢。

因为无论传递什么,
LastIndexOf
都会返回一些值,所以您应该检查结果是否有效

当字符串没有
'@'
符号时,
LastIndexOf
生成
-1
。将其传递到
子字符串
会给您一个从零到负1的无效范围

以下是解决此问题的方法:

// Find the position of '@', and store it in a variable
var pos = email.LastIndexOf("@");
// Check the position for negative value before passing it to Substring
var emailTrim = pos >= 0 ? email.Substring(0, pos) : email;
改用
Split()

string emailTrimmed = email.Split('@')[0];