【问题标题】:Public function returning a list c#公共函数返回一个列表c#
【发布时间】:2021-12-12 11:56:19
【问题描述】:

我有一段代码,它基本上创建了一个对象列表,这段代码稍后将成为更大程序的一部分,我需要一个函数来将列表返回给程序。我试过这样的事情:

//RETURN LIST FUNCTION
public List<WynikPorownania> Zwrlista()
{
    return listatf;
}            

但它不能完成这项工作,因为它只能在这段代码中使用,而且我不能使用 public 说明符。这是我的代码:

using System;
using FirebirdSql.Data.FirebirdClient;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace dokselect
{
    class indexstan
    {
        public string index;
        public double standysp;
    }

    class WynikPorownania
    {
        public string Indeks;
        public int Ilosc;
        public override string ToString()
        {
            return Indeks + " : " + Ilosc;
        }

    }
    class Program
    {
        public static void Main()
        {
            try
            {
                ///////CONNECTION

            string conn = "CONNECTION STRING IS HERE";
            FbConnection myConnection = new FbConnection(conn);
            FbDataReader myReader = null;

            string sql = "select KARTOTEKA.indeks,STANMAG.standysp FROM kartoteka INNER JOIN stanmag using(ID_KARTOTEKA) WHERE stanmag.ID_MAGAZYN=10002;";
            FbCommand myCommand = new FbCommand(sql, myConnection);

            myConnection.Open();
            myReader = myCommand.ExecuteReader();

            ///////LIST lista1
            List<indexstan> listadb = new List<indexstan>();
            double standysp;
            string index;
            while (myReader.Read())
            {
                index = myReader[0].ToString();
                standysp = Convert.ToDouble(myReader[1]);
                if(standysp<0)
                    {
                        standysp = 0;
                    }
                listadb.Add(new indexstan { index=index, standysp=standysp });
                //Console.WriteLine(myReader[0].ToString());
            }
            myConnection.Close();
            Console.WriteLine(listadb.Count);


                //RETURN STANDYSP FUNCTION
                double zwr(string myIndex)
                {
                    var result = listadb.FirstOrDefault(listadb => listadb.index == myIndex)?.standysp;
                    return result ?? -1;
                }
                //zwr("EMPIS_DESKA_FASOLKA");

                //READ FROM TXT AND RETURN HIGHER
                string path = "C:/Users/Praktykant/Documents/textdocs/dok1.txt";
            
                List<WynikPorownania> listatf = File.ReadAllLines(path).Select(line =>
                {   
                    var linia = line.Split("=");
                    string index = linia[0];
                    int value = int.Parse(linia[1]);
                    if(value<0)
                    {
                        value = 0;
                    }
                    if(zwr(index)==-1)
                    {
                        return new WynikPorownania { Indeks = index, Ilosc = (int)zwr(index) };
                    }
                    else
                    {
                        return new WynikPorownania { Indeks = index, Ilosc = (int)Math.Max(value, zwr(index)) };
                    }
                }).ToList();
                //DISPLAY ALL LISTATF CLASSES
                foreach (WynikPorownania WynikPorownania in listatf)
                {
                    Console.WriteLine(WynikPorownania);
                }
                //RETURN LIST FUNCTION
                public List<WynikPorownania> Zwrlista()
                {
                    return listatf;
                }

            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine("Nie znaleziono pliku z podanej sciezki. Blad zwrocil: "+ex);
            }
            catch (FormatException ex)
            {
                Console.WriteLine("Podaj indeksy i wartosci w formacie 'indeks=wartosc'. Blad zwrocil: "+ex);
            }
            catch (NullReferenceException ex)
            {
                Console.WriteLine("Nie podales prawidlowego indeksu. Blad zwrocil: "+ex);
            }
            catch (IndexOutOfRangeException ex)
            {
                Console.WriteLine("Zly format. Blad zwrocil: "+ ex);
            }
        }
    }
}

编辑: 我阅读了您的一些建议,我想我理解问题所在。我以这种方式重新排列了代码:

using System;
using FirebirdSql.Data.FirebirdClient;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace dokselect
{
    class indexstan
    {
        public string index;
        public double standysp;
    }

    public class WynikPorownania
    {
        public string Indeks;
        public int Ilosc;
        public override string ToString()
        {
            return Indeks + " : " + Ilosc;
        }

    }
    class Program
    {
        public List<indexstan> listadatabase()
        {
            string conn = "CONNECTION STRING";
            FbConnection myConnection = new FbConnection(conn);
            FbDataReader myReader = null;

            string sql = "select KARTOTEKA.indeks,STANMAG.standysp FROM kartoteka INNER JOIN stanmag using(ID_KARTOTEKA) WHERE stanmag.ID_MAGAZYN=10002;";
            FbCommand myCommand = new FbCommand(sql, myConnection);

            myConnection.Open();
            myReader = myCommand.ExecuteReader();

            ///////LIST lista1
            List<indexstan> listadb = new List<indexstan>();
            double standysp;
            string index;
            while (myReader.Read())
            {
                index = myReader[0].ToString();
                standysp = Convert.ToDouble(myReader[1]);
                if (standysp < 0)
                {
                    standysp = 0;
                }
                listadb.Add(new indexstan { index = index, standysp = standysp });
                //Console.WriteLine(myReader[0].ToString());
            }
            myConnection.Close();
            Console.WriteLine(listadb.Count);
            return listadb;
        }
        public double zwr(string myIndex)
        {
            var result = listadb.FirstOrDefault(listadb => listadb.index == myIndex)?.standysp;
            return result ?? -1;
        }
        public List<WynikPorownania> lista()
        {
            string path = "C:/Users/Praktykant/Documents/textdocs/dok1.txt";
            List<WynikPorownania> listatf = File.ReadAllLines(path).Select(line =>
            {
                var linia = line.Split("=");
                string index = linia[0];
                int value = int.Parse(linia[1]);
                if (value < 0)
                {
                    value = 0;
                }
                if (zwr(index) == -1)
                {
                    return new WynikPorownania { Indeks = index, Ilosc = (int)zwr(index) };
                }
                else
                {
                    return new WynikPorownania { Indeks = index, Ilosc = (int)Math.Max(value, zwr(index)) };
                }
            }).ToList();
            return listatf;
        }
        public static void Main()
        {
            try
            {
                
                
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine("Nie znaleziono pliku z podanej sciezki. Blad zwrocil: "+ex);
            }
            catch (FormatException ex)
            {
                Console.WriteLine("Podaj indeksy i wartosci w formacie 'indeks=wartosc'. Blad zwrocil: "+ex);
            }
            catch (NullReferenceException ex)
            {
                Console.WriteLine("Nie podales prawidlowego indeksu. Blad zwrocil: "+ex);
            }
            catch (IndexOutOfRangeException ex)
            {
                Console.WriteLine("Zly format. Blad zwrocil: "+ ex);
            }
        }
    }
}

但我不认为它是正确的,甚至视觉工作室突出了错误,说listadb在这种情况下不存在。我真的不知道从这里去哪里。附言。抱歉,如果代码不是 100% 用英文编写,但我只是一家公司的实习生,我正在按照他们告诉我的方式命名变量和函数,将来在做项目时,我一定会记得使用英语:D

【问题讨论】:

  • 你在这里使用本地函数的原因是什么?
  • 我建议您将创建列表的代码提取到它自己的方法中,可以公开(一旦 WynikPorownania 公开)。然后,您可以从 Main 调用该方法。
  • 无关:特别是在国际环境中,坚持英文命名是有好处的,因此绝大多数读者可以理解类和属性等应该是什么。此外,始终使用standard dotnet naming conventions 是个好主意。 (+docs.microsoft.com/en-us/dotnet/csharp/fundamentals/…)
  • 别那么苛刻,他只是“C:/Users/Praktykant”(英语-实习生)
  • @Auditive 没有人(故意)苛刻。这些都是合法的改进建议。这不就是我们来这里的目的吗? 而且:如果我们是认真的,我们永远只是实习生。没有一天我没有学到任何新东西。

标签: c# list return


【解决方案1】:

你好像把事情搞混了:

public 表示声明为public 的方法可以被其他对象使用。

您的函数嵌入在方法中,因此,它不是public 方法:它只是一个函数,嵌入在方法中,因此只能从该方法中访问。

【讨论】:

  • 此外,列表定义 List&lt;WynikPorownania&gt; listatf 是 Main try ... catch 块的本地定义,因此将超出范围且无法公开访问。
【解决方案2】:

我只是将所有内容都放入一个函数中,它就可以工作。如果将来有人遇到这个问题,下面是它的外观:

using System;
using FirebirdSql.Data.FirebirdClient;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace dokselect
{
    class indexstan
    {
        public string index;
        public double standysp;
    }

    public class WynikPorownania
    {
        public string Indeks;
        public int Ilosc;
        public override string ToString()
        {
            return Indeks + " : " + Ilosc;
        }

    }
    class Program
    {
        public static List<WynikPorownania> funkcjalista()
        {
            ///////CONNECTION
                string conn = "CONNECTION STRING";
                FbConnection myConnection = new FbConnection(conn);
                FbDataReader myReader = null;

                string sql = "select KARTOTEKA.indeks,STANMAG.standysp FROM kartoteka INNER JOIN stanmag using(ID_KARTOTEKA) WHERE stanmag.ID_MAGAZYN=10002;";
                FbCommand myCommand = new FbCommand(sql, myConnection);

                myConnection.Open();
                myReader = myCommand.ExecuteReader();

                ///////LIST lista1
                List<indexstan> listadb = new List<indexstan>();
                double standysp;
                string index;
                while (myReader.Read())
                {
                    index = myReader[0].ToString();
                    standysp = Convert.ToDouble(myReader[1]);
                    if (standysp < 0)
                    {
                        standysp = 0;
                    }
                    listadb.Add(new indexstan { index = index, standysp = standysp });
                    //Console.WriteLine(myReader[0].ToString());
                }
                myConnection.Close();
                Console.WriteLine(listadb.Count);


                //RETURN STANDYSP FUNCTION

                double zwr(string myIndex)
                {
                    var result = listadb.FirstOrDefault(listadb => listadb.index == myIndex)?.standysp;
                    return result ?? -1;
                }

                //zwr("EMPIS_DESKA_FASOLKA");

                //READ FROM TXT AND RETURN HIGHER
                string path = "C:/Users/Praktykant/Documents/textdocs/dok1.txt";
            


                List<WynikPorownania> listatf = File.ReadAllLines(path).Select(line =>
                {
                    var linia = line.Split("=");
                    string index = linia[0];
                    int value = -1;
                    try
                    {
                        value = int.Parse(linia[1]);
                    }
                    catch (IndexOutOfRangeException)
                    {
                        index += " - ZLE ZAPISANA LINIA";
                    }
                    catch (FormatException)
                    {
                        index += " - PODANO ZLA WARTOSC";
                    }


                    if (zwr(index) == -1)
                    {
                        return new WynikPorownania { Indeks = index, Ilosc = (int)zwr(index) };
                    }
                    else
                    {
                        if (value < 0)
                        {
                            value = 0;
                        }
                        return new WynikPorownania { Indeks = index, Ilosc = (int)Math.Max(value, zwr(index)) };
                    }
                }).ToList();
            
                //DISPLAY ALL LISTATF CLASSES

                foreach (WynikPorownania WynikPorownania in listatf)
                {
                    Console.WriteLine(WynikPorownania);
                }
            return listatf;
            
        }
        public static void Main()
        {
            funkcjalista();
        }
    }
}

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。
猜你喜欢
  • 2018-11-28
  • 2010-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-31
  • 1970-01-01
相关资源
最近更新 更多