Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将新项添加到此数组?_C#_.net_Arrays_C# 4.0_.net 4.5 - Fatal编程技术网

C# 如何将新项添加到此数组?

C# 如何将新项添加到此数组?,c#,.net,arrays,c#-4.0,.net-4.5,C#,.net,Arrays,C# 4.0,.net 4.5,我有一门课- public class PropertyModel { public string Name { get; set; } public string Value { get; set; } } 这是数组,它是我的请求模型的一部分 public PropertyModel[] Properties { get; set; } 此数组由用户填充,有时也可以为空 无论是否填充-我想添加一个名称/值对-[Origin,WEB]始终添加到此数组 如何进行阵列加法?我应该

我有一门课-

public class PropertyModel
{
    public string Name { get; set; }
    public string Value { get; set; }
}
这是数组,它是我的请求模型的一部分

public PropertyModel[] Properties { get; set; }
此数组由用户填充,有时也可以为空

无论是否填充-我想添加一个名称/值对-[Origin,WEB]始终添加到此数组


如何进行阵列加法?我应该先将其转换为列表,然后添加,再将其转换回数组吗?

实现这一点的方法有很多,但如果您只想添加一项,请尝试以下代码

 PropertyModel[] arr = {};
 var toAdd = new PropertyModel() { Name = "Origin", Value = "WEB" };
 arr = arr.Concat(new PropertyModel[] { toAdd }).ToArray();
您可以使用List而不是PropertyModel[]数组。使用列表,您可以简化代码,如下所示:

public static List<PropertyModel> GetAll()
{
    List<PropertyModel> myList= new List<PropertyModel>();
    myList.Add(new PropertyModel(){Name = "Anna", Value = "500$"});
    myList.Add(new PropertyModel(){Name = "Michellen", Value = "520$"});

    return myList;
}
private List<PropertyModel> _Properties = new List<PropertyModel>();
public List<PropertyModel> MyProperty
{
   get { return _Properties; }
   set { myVar = _Properties; }
}
这是密码

//to use the function
    public static void Main()
    {
       Properties = GetAll().ToArray();

    }
尝试使用ArrayList:


添加和使用对象更容易,并且无论何时需要数组,都可以调用.ToArray方法。

这次您应该使用List来代替PropertyModel[]。由于您不知道集合的最终大小,因此用户可能会在稍后向集合中添加新项目。因此,我建议您这样定义属性:

public static List<PropertyModel> GetAll()
{
    List<PropertyModel> myList= new List<PropertyModel>();
    myList.Add(new PropertyModel(){Name = "Anna", Value = "500$"});
    myList.Add(new PropertyModel(){Name = "Michellen", Value = "520$"});

    return myList;
}
private List<PropertyModel> _Properties = new List<PropertyModel>();
public List<PropertyModel> MyProperty
{
   get { return _Properties; }
   set { myVar = _Properties; }
}
当你面对同样的困惑时,请记住以下几点:

如果您知道集合的最终大小,您可以 使用T[]或List。 如果你不知道最后的结果 大小收集大小因使用列表而异。
调整数组大小,以便在以后添加项目,而最初不知道集合的长度,那么为什么要坚持使用数组呢?为什么不使用列表呢?不要使用ArrayList。到目前为止,它已经被弃用了10多年。使用通用列表