gpt4 book ai didi

c# - 您如何对 FileHelpers 进行自定义验证?

转载 作者:行者123 更新时间:2023-11-30 21:08:03 25 4
gpt4 key购买 nike

我想抛出一个异常,说明我们有一个无效的电子邮件地址,因为在我们获得一个有效的电子邮件地址之前我不想继续。这是我想做的地方吗?如果是,怎么做?

void Engine_AfterReadRecord(EngineBase engine, FileHelpers.Events.AfterReadEventArgs<UserInfoFromAd> e){
bool isEmailValid = IsEmailValid(e.Record.Email);
if (!isEmailValid){
//I want to throw exception
}
}

最佳答案

AfterReadRecord 事件中抛出异常是可以的,但是你需要设置ErrorModeSaveAndContinue。这告诉引擎将错误保存到 Engine.ErrorManager.Errors 并继续导入。导入后,您可以处理错误。

这是一个示例程序:

[DelimitedRecord("|")]
public class MyClass
{
public string Field1 { get; set; }
public int Field2 { get; set; }
public string Email { get; set; }
}

class Program
{
static void Main(string[] args)
{
var engine = new FileHelperEngine<MyClass>();
engine.AfterReadRecord += new FileHelpers.Events.AfterReadHandler<MyClass>(engine_AfterReadRecord);
engine.ErrorMode = ErrorMode.SaveAndContinue;
// import a record with an invalid Email
MyClass[] validRecords = engine.ReadString("Hello|23|World");
ErrorInfo[] errors = engine.ErrorManager.Errors;
Assert.AreEqual(1, engine.TotalRecords); // 1 record was processed
Assert.AreEqual(0, validRecords.Length); // 0 records were valid
Assert.AreEqual(1, engine.ErrorManager.ErrorCount); // 1 error was found
Assert.That(errors[0].ExceptionInfo.Message == "Email is invalid");
}

static bool IsEmailValid(string email)
{
return false;
}

static void engine_AfterReadRecord(EngineBase engine, FileHelpers.Events.AfterReadEventArgs<MyClass> e)
{
bool isEmailValid = IsEmailValid(e.Record.Email);
if (!isEmailValid)
{
throw new Exception("Email is invalid");
}
}
}

关于c# - 您如何对 FileHelpers 进行自定义验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9918293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com