上述代码中age为空,如何修改
时间: 2024-04-15 08:31:20 浏览: 27
如果在提取用户信息的过程中,年龄属性为空,您可以通过添加条件语句来处理该情况。以下是修改后的示例代码```csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
public class UserInfo
{
public string Name { get; set; }
public string Age { get; set; }
public string Gender { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
public class Program : Form
{
private Button extractButton;
public Program()
{
extractButton = new Button();
extractButton.Text = "提取用户信息";
extractButton.Click += ExtractButton_Click;
Controls.Add(extractButton);
}
private void ExtractButton_Click(object sender, EventArgs e)
{
string filePath = "path/to/your/txt/file.txt";
UserInfo userInfo = ExtractUserInfo(filePath);
if (userInfo.Age != null)
{
MessageBox.Show($"姓名: {userInfo.Name}\n" +
$"年龄: {userInfo.Age}\n" +
$"性别: {userInfo.Gender}\n" +
$"电话: {userInfo.Phone}\n" +
$"邮箱: {userInfo.Email}");
}
else
{
MessageBox.Show("无法提取年龄信息");
}
}
private UserInfo ExtractUserInfo(string filePath)
{
string content = File.ReadAllText(filePath);
string name = GetMatchValue(content, @"姓名:([\w\s]+)");
string age = GetMatchValue(content, @"年龄:(\d+)");
string gender = GetMatchValue(content, @"性别:([\w\s]+)");
string phone = GetMatchValue(content, @"电话:(\d+)");
string email = GetMatchValue(content, @"邮箱:([\w\.]+@[\w\.]+)");
UserInfo userInfo = new UserInfo
{
Name = name,
Age = age,
Gender = gender,
Phone = phone,
Email = email
};
return userInfo;
}
private string GetMatchValue(string content, string pattern)
{
Match match = Regex.Match(content, pattern);
return match.Success ? match.Groups[1].Value : null;
}
public static void Main(string[] args)
{
Application.Run(new Program());
}
}
```
在这个修改后的示例代码中,我们添加了一个条件语句来检查年龄属性是否为空。如果年龄不为空,将使用 `MessageBox` 显示用户信息。如果年龄为空,则显示一条消息表示无法提取年龄信息。
请确保将 `filePath` 替换为实际的文件路径。运行程序后,点击按钮即可触发提取操作,并根据情况显示用户信息或者提示无法提取年龄信息。