企业库验证应用程序模块之配置文件模式:
1. 新建一个控制台应用程序,并创建一个Customer类,其代码如下所示:

using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
using Microsoft.Practices.EnterpriseLibrary.Validation;
namespace ConsoleApplication1
{
class Program
{
staticvoid Main(string[] args)
{
}
publicclass Customer
{
publicstring CustomerName;
public Customer(string customerName)
{
this.CustomerName = customerName;
}
publicint Test()
{
return-5;
}
}
}
2. 运行EntLibConfig.exe, 选择Blocks菜单 ,单击 Add Validation Settings .
3. 点击Validated Types区块右上角的加号按钮,然后点击 Add Type to Validate,这时会要你选择要验证的类,因为我们是想对Customer类的属性进行验证,所以我们要导入我们刚刚创建的类,点击并Add from File找到我们的应用程序Debug文件夹下的ConsoleApplication1.exe(根据你创建时起的名字而不同),Customer类就包含在这个程序内:
4. 导入后,我们就可以看到多了个ConsoleApplication1程序集,接着我们要选择它所包含的Customer类,如下图所示,选择后点击OK:
5. 在Customer面板上右键— Add Validation Ruleset:
6. 在设置Customer面板中的Defaule Ruleset属性为新创建的Validation Ruleset,接着在Validation Ruleset面板右键—Select Members,在弹出的选择框中选择
7. 在弹出的成员选择界面,我们选择要测试的Test方法和CustomerName属性:
8. 在Field:CustomerName面板上右键—Add Validators –Add Not Null Validator:
9. 对该验证器的设置如下图所示:
10. 在Method:Test面板上右键—Add Validators –Add Range Validator:
11. 对该验证器的设置如下图所示:
12. 点击 File菜单,单击 Save,保存为一个App.config文件,可以先保存到桌面,之后要用到它.
13. 将App.config添加到工程中,并添加需要的引用,如图所示:
14. 测试:

using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
using Microsoft.Practices.EnterpriseLibrary.Validation;
namespace ConsoleApplication1
{
class Program
{
staticvoid Main(string[] args)
{
Validator<Customer> customerValidator = ValidationFactory.CreateValidator<Customer>("Validation Ruleset");
Customer myCustomer =new Customer(null);
ValidationResults r = customerValidator.Validate(myCustomer);
if (!r.IsValid)
{
for (int i =0; i < r.Count; i++)
{
Console.WriteLine("出错{0}:"+ r.ElementAt(i).Message, i +1);
}
}
else
{
Console.WriteLine("正确");
}
}
}
publicclass Customer
{
publicstring CustomerName;
public Customer(string customerName)
{
this.CustomerName = customerName;
}
publicint Test()
{
return-5;
}
}
}
15. 运行结果:
Demo下载 \( ̄[]  ̄ \)
出处:http://www.cnblogs.com/huangcong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构