简体   繁体   English

如何在C#中的foreach循环中实例化并添加到类

[英]How can I instantiate and add to a class inside a foreach loop in C#

I have code that I want to use to log error messages. 我有要用于记录错误消息的代码。 I made two classes like this to hold the messages: 我制作了两个这样的类来保存消息:

public class HttpStatusErrors
{
    public HttpStatusErrors()
    {
        this.Details = new List<HttpStatusErrorDetails>();
    }
    public string Header { set; get; }
    public IList<HttpStatusErrorDetails> Details { set; get; }
}
public class HttpStatusErrorDetails
{
    public HttpStatusErrorDetails()
    {
        this.Details = new List<string>();
    }
    public string Header { set; get; }
    public IList<string> Details { set; get; }
}

I think this is a good way to do this but I am not 100% sure and would welcome any suggestions. 我认为这是执行此操作的好方法,但是我不确定100%会接受任何建议。

What I would like to do is in the first class to store the Header which in my example would be "Validation Messages". 我想在第一类中存储Header ,在我的示例中为“ Validation Messages”。 Then in the Detail object I would like to store another Header that showed the entity with the error and finally in the Details store the validation errors. 然后在Detail对象中,我想存储另一个Header ,该Header显示有错误的实体,最后在Details存储验证错误。

What I am confused on is how should I instantiate the classes. 我很困惑的是我应该如何实例化这些类。 I have done this so far. 到目前为止,我已经做到了。 I think this is correct. 我认为这是正确的。 But how can I add the details that I need to add: 但是如何添加需要添加的详细信息:

catch (DbEntityValidationException ex)
{
    var msg = new HttpStatusErrors();
    msg.Header = "Validation Error";

    foreach (var eve in ex.EntityValidationErrors)
    {
        var header = string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
            eve.Entry.Entity.GetType().Name, eve.Entry.State);
        foreach (var ve in eve.ValidationErrors)
        {
            var detail = string.Format("- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage);
        }

    }

}.

Instantiate collections in Details properties. 在“ Details属性中实例化集合。 Instantiate new items, and add them to collections in loop: 实例化新项目,并将其添加到循环中的集合中:

var msg = new HttpStatusErrors();
msg.Header = "Validation Error";
msg.Details = new List<HttpStatusErrorDetails>();

foreach (var eve in ex.EntityValidationErrors)
{
    var detail = new HttpStatusErrorDetails()
    detail.Header = String.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
        eve.Entry.Entity.GetType().Name, eve.Entry.State);

    detail.Details = new List<string>();
    foreach (var ve in eve.ValidationErrors)
    {
        detail.Details.Add(String.Format("- Property: \"{0}\", Error: \"{1}\"",
            ve.PropertyName, ve.ErrorMessage));
    }

    msg.Details.Add(detail);
}

Btw you can use LINQ for that: 顺便说一句,您可以为此使用LINQ:

var msg = new HttpStatusErrors();
msg.Header = "Validation Error";
msg.Details =
    ex.EntityValidationErrors
      .Select(eve => new HttpStatusErrorDetails {
                Header = String.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State)
                Details = eve.ValidationErrors
                         .Select(ve => String.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage))
                         .ToList()
       }).ToList();

Also I like extension methods syntax: 我也喜欢扩展方法语法:

 public static HttpStatusErrors ToHttpStatusErrors(
      this DbEntityValidationException ex)
 {
      return new HttpStatusErrors {
          Header = "Validation Error",
          Details = ex.EntityValidationErrors
                      .Select(eve => eve.ToHttpStatusErrorDetails())
                      .ToList()
      };
 }

 public static HttpStatusErrorDetails ToHttpStatusErrorDetails(
      this DbEntityValidationResult eve)
 {
      return new HttpStatusErrorDetails {
        Header = String.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                               eve.Entry.Entity.GetType().Name, eve.Entry.State),
        Details = eve.ValidationErrors
                     .Select(ve => ve.ToErrorDescription())
                     .ToList()
      };
 }

 public static string ToErrorDescription(
      this DbValidationError ve)
 {
      return String.Format("- Property: \"{0}\", Error: \"{1}\"",
                           ve.PropertyName, ve.ErrorMessage);
 }

Usage of such methods will be like: 此类方法的用法如下:

catch (DbEntityValidationException ex)
{
    var msg = ex.ToHttpStatusErrors();
}

Try the following: 请尝试以下操作:

foreach (var eve in ex.EntityValidationErrors)
{
    //New Details Entity
    var errorDetail = new HttpStatusErrorDetails();

    //Fill in Header
    errorDetail.Header = string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
        eve.Entry.Entity.GetType().Name, eve.Entry.State);

    //Fill Add a detail for each validation error
    foreach (var ve in eve.ValidationErrors)
    {
        errorDetail.Details.Add(string.Format("- Property: \"{0}\", Error: \"{1}\"",
            ve.PropertyName, ve.ErrorMessage));
    }

    //Add Detail to header
    msg.Details.Add(errorDetail);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM