需要判断用户输入的数据并在输入错误的情况下在屏幕上显示通知.我用了下面的方法,但在我看来,它不太符合"不重复自己"的原则.有没有人对简化有什么 idea ?

int productid = 0;
string errorMessage = "Неправильный формат данных:\n",
       productName = "", productGroup = "", productType = "";
if (!int.TryParse(ProductIdTB.Text, out productId))
{
    errorMessage += "+ Номер продукта\n";
}
if (string.IsNullOrEmpty(ProductNameTB.Text))
{
    errorMessage += "+ Название продукта\n";
}
else
{
    productName = ProductNameTB.Text;
}
if (string.IsNullOrEmpty(ProductGroupTB.Text))
{
    errorMessage += "+ Группа продукта\n";
}
else
{
    productGroup = ProductGroupTB.Text;
}
if (string.IsNullOrEmpty(ProductType.Text))
{
    errorMessage += "+ Вид продукта";
}
else
{
    productType = ProductType.Text;
}
if (errorMessage.Split(' ').Length > 1)
{
    MessageBox.Show(errorMessage);
    return;
}

推荐答案

我可以想象构建一个类,它为您执行判断并收集字符串或字符串列表中的所有错误.

class ErrorMessageBuilder
{
    string totalmessage = "";

    void AppendErrorIfEmpty(TextBox t, string textboxname)
    {
        if (t.Text.IsNullOrEmpty())
        {
            totalmessage += textboxname + " can't be empty" + Environment.NewLine;
        }    
    }

    void AppendErrorIfNotInt(TextBox t, string textboxname)
    {
         int value;
         if (!int.TryParse(t.Text, out value))
         {
             totalmessage += textboxname + " must be an integer number"  + Environment.NewLine;
         }
    }
}

这将使代码减少到

var emb = ErrorMessageBuilder();
emb.AppendErrorIfNotInt(ProductIdTB, "Product ID");
emb.AppendErrorIfEmpty(ProductNameTB, "Product Name");
...

因为这看起来像是WinForms开发的,所以你也可以看看ErrorProvider class.与工具提示一样,它允许每个控件显示一条错误消息.也许这会更方便用户使用.

Csharp相关问答推荐

如何使用Automapper映射两个嵌套列表

AsNoTrackingWithIdentitySolutions()似乎不起作用?

Take()方法如何与IAsyncEnumerable一起使用

如何在页面重新加载后保持菜单切换状态

Blazorise折线图仅绘制数据集的一部分

Blazor Web App WASM的两个独立项目令人困惑

Regex字母数字校验

如何允许数组接受多个类型?

升级后发出SWITCH语句

实体框架-IsRequired()与OnDelete()

如何使用类似于[SELECT*FROM&Q;&Q;WHERE&Q;]SQL查询的System.Data.Entity创建查询?

FakeItEasy自动嘲弄内容

如何在绑定到数据库的datagridview中向上或向下移动行

Autofac -动态实例化:手动传递构造函数

如何使用.NET 8.0中新的CompositeFormat类?

从HTML元素获取 colored颜色

RavenDb:为什么在字符串==空的情况下过滤会过滤得太多?

如何在特定时间间隔运行多个后台任务?

Azure队列触发器未使用隔离的工作进程执行

与Visual Studio 2022中的.NET框架相比,如何在.NET Core 6中获取错误输出的窗口句柄