简体   繁体   English

如何在C#中的函数中动态创建列表

[英]How to dynamically create a List in a function in C#

I have a code written in c. 我有一个用c编写的代码。 I have a pointer to int in main and I pass it to a function. 我在main中有一个指向int的指针,并将其传递给一个函数。 This function allocates memory and populates the array, then it returns. 此函数分配内存并填充数组,然后返回。 Basically looks like this: 基本上看起来像这样:

main()
{
  int* array;
  function(&array);
}

void function(int** array)
{
  int size = 25;
  *array = malloc(size);
  (*array)[0] = 42;
}

Size is not known in main. 尺寸主要未知。 How do I do this in C#? 如何在C#中执行此操作? I tried with List but I cannot make it work. 我尝试使用List,但无法使其正常工作。 I have tried both List and ref List, and they both give Index was out of range. 我已经尝试了List和ref List,它们都给Index超出了范围。

EDIT: 编辑:

This works fine 这很好

class Program
{
    static void function(List<int> array)
    {
        array.Add(42);
    }

    static void Main(string[] args)
    {
        List<int> array = new List<int>();
        function(array);
    }
}

And this one too 还有这个

class Program
{
    static void function(out int[] array)
    {
        array = new int[25];
        array[0] = 42;
    }

    static void Main(string[] args)
    {
        int[] array;
        function(out array);
    }
}

But the following throws an exception 但是以下引发异常

class Program
{
    static void function(out List<int> array)
    {
        array = new List<int>(25);
        array[0] = 42;
    }

    static void Main(string[] args)
    {
        List<int> array;
        function(out array);
    }
}
Class Demo
{


 static void main (string[] args)
 {
    var result=Add();
    Console.WriteLine(result[0]);
 }

  static List<int> Add ()
  {
    var listOfints= new List<int>();
    listOfints.Add(42); //either this or declare an array of integers and get it initialized by reading the user value and pass the same as param here to initialize and return the array
    return listOfints;
  }

}

has the ref keyword for this purpose. 为此, 具有ref关键字。 Although it is not required in this case because an array is a reference type anyway it is a good idea nevertheless because it conveys the design intent. 尽管在这种情况下并不需要,因为无论如何数组都是引用类型,但这是一个好主意,因为它传达了设计意图。 Better yet to use the out keyword as the argument to the function doesn't need to be initialized before the call. 最好还是使用out关键字作为该函数的参数,而无需在调用之前初始化。

Try this: 尝试这个:

class Program
{
    static void Main(string[] args)
    {
        int[] a;
        function(out a);
        Debug.WriteLine(a.Length);
    }

    public static void function(out int[] array)
    {
        array=new int[25];
        array[0]=42;
    }
}

Edit 1 - Alternate way with returning an array 编辑1-返回数组的替代方法

class Program
{
    static void Main(string[] args)
    {
        int[] a = CreateArray();
        Debug.WriteLine(a.Length);
    }

    public static int[] CreateArray() 
    {
        int[] array=new int[25];
        array[0]=42;
        return array;
    }
}

Edit 2 - Example with two out parameters 编辑2-具有两个out参数的示例

class Program
{
    static void Main(string[] args)
    {
        int[] akw, zuk;
        function(out akw, out zuk);
        Debug.WriteLine(akw.Length);
        Debug.WriteLine(zuk.Length);
    }

    public static void function(out int[] A, out int[] B) 
    {
        A=new int[25];
        B=new int[15];
        A[0]=42;
        B[0]=21;
    }
}

I think the reason that you're having problems assigning value [0] to ac# list is that unless you create a List<> collection with a predefined start size it will be empty. 我认为您在将值[0]分配给ac#列表时遇到问题的原因是,除非您创建具有预定义起始大小的List <>集合,否则它将为空。 Thus entry [0] is null and can't be set. 因此,条目[0]为空,无法设置。

If you want to directly access element 0, use this: 如果要直接访问元素0,请使用以下命令:

  void function(out List<int> list)
  {
     list = new List<int>(25);
     list[0] = 42;
  }

If instead you don't need to / know the initial allocation size of the List, use this: (recommended IMHO) 相反,如果您不需要/不知道列表的初始分配大小,请使用以下命令:(推荐的恕我直言)

  void function(out List<int> list)
  {
     list = new List<int>();
     list.Add(42);
  }

Good luck! 祝好运!

Another way (Although it's recommended to use a List<int> ) 另一种方法(尽管建议使用List<int>

Replace int * with out int[] out int[]替换int *

public class Program
{
    public static void Main()
    {
        int[] array;
        function(out array);
        Console.WriteLine(array[0]);
    }

    static void function(out int[] array)
    {
        int size = 25;
        array = new int[size];
        array[0] = 42;
    }
}

Output 输出量

42

As mentioned above c# uses references. 如上所述,c#使用引用。 Pointers are supported but you would need to write unmanaged code.. 支持指针,但是您需要编写非托管代码。
More info about references here https://msdn.microsoft.com/en-us/library/14akc2c7.aspx 有关参考的更多信息,请参见此处https://msdn.microsoft.com/zh-cn/library/14akc2c7.aspx

A sample is below. 下面是一个示例。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace alistnamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> my_list=new List<int>();
            functionaddtolist(ref my_list);
            for(int i=0;i<my_list.Count;i++)
            {
                Console.WriteLine("List item " + i.ToString() + "=" + my_list[i]);
            }
        }

        static void functionaddtolist(ref List<int> mylist_ref)
        {
            mylist_ref.Add(42);             //Add one element

        }
    }
}

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

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