[英]How can I make a C# class instantiate another class in its constructor?
I created the following: 我创建了以下内容:
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.Errors = new List<string>();
}
public string Error { set; get; }
public IList<string> Errors { set; get; }
}
In my code I am using it like this: 在我的代码中我使用它像这样:
var msg = new HttpStatusErrors();
msg.Header = "Validation Error";
foreach (var eve in ex.EntityValidationErrors) {
msg.Details. // Valid so far
msg.Details.Error // Gives the error below:
The Ide recognizes msg.Details as being valid but when I try to write the second line I get: Ide将msg.Details视为有效,但当我尝试编写第二行时,我得到:
Error 3 'System.Collections.Generic.IList<TestDb.Models.Http.HttpStatusErrorDetails>'
does not contain a definition for 'Error' and no extension method 'Error' accepting a first
argument of type 'System.Collections.Generic.IList<TestDb.Models.Http.HttpStatusErrorDetails>'
could be found (are you missing a using directive or an assembly reference?)
C:\K\ST136 Aug 16\WebUx\Controllers\ProblemController.cs 121 33 WebUx
Is there something I am doing wrong? 有什么我做错了吗? I thought the way I had this set up that new Lists would be created when the first class was created.
我认为我设置的方式是在创建第一个类时创建新的列表。
msg.Details
returns a List
object. msg.Details
返回一个List
对象。 List<T>
does not have an Errors
property. List<T>
没有Errors
属性。 You need to access a specific element in your list, and only then will you have your Errors
property. 您需要访问列表中的特定元素,然后才会拥有
Errors
属性。
For example: 例如:
msg.Details[0].Error
In your code you might want to make sure that msg.Details
contains elements before trying to access them, or better yet iterate over them in a foreach
loop. 在您的代码中,您可能希望确保
msg.Details
在尝试访问它们之前包含元素,或者更好地在foreach
循环中迭代它们。
Details is a collection. 细节是一个集合。 The property
Error
belongs to an item in the collection Details. 属性
Error
属于集合Details中的项目。 There is no property Error
on that collection Details 该集合详细信息没有属性
Error
you are tying to go to Details
which is a IList<HttpStatusErrorDetails>
. 你想要去一个
IList<HttpStatusErrorDetails>
Details
。
if you want to go through the items in that list u need go over them for example 如果你想要查看该列表中的项目,你需要仔细阅读它们
msg.Details[number].Errors
or 要么
foreach(HttpStatusErrorDetails err in msg.Details)
{
err.Errors
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.