You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#实现返回自定义对象列表的公共函数及作用域问题解决

错误原因

listadb是你在listadatabase()方法内部定义的局部变量,C#中局部变量的作用域仅限于定义它的代码块,出了listadatabase()方法后这个变量就失效了,所以zwr()方法自然找不到这个变量。

修复方案

因为你需要对外提供可调用的公共方法,建议把业务逻辑从Program类中抽离成独立的服务类,方便后续集成到其他项目,修改后完整代码如下:

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

namespace dokselect
{
    // 改为公共类,外部项目可访问
    public class indexstan
    {
        public string index;
        public double standysp;
    }

    // 保持公共类,对外返回结果用
    public class WynikPorownania
    {
        public string Indeks;
        public int Ilosc;
        public override string ToString()
        {
            return Indeks + " : " + Ilosc;
        }
    }

    // 新增独立业务服务类,所有逻辑封装在这里,方便外部调用
    public class PorownanieMagazynuService
    {
        // 把listadb定义为类私有字段,类内所有方法都能访问
        private List<indexstan> _listadb;
        // 可配置的参数,你也可以做构造方法参数动态传入
        private string _connString = "你的数据库连接字符串";
        private string _txtPath = "C:/Users/Praktykant/Documents/textdocs/dok1.txt";

        // 构造方法,初始化时自动查询数据库
        public PorownanieMagazynuService()
        {
            _listadb = PobierzDaneZBazy();
        }

        // 私有方法,仅内部调用查询数据库
        private List<indexstan> PobierzDaneZBazy()
        {
            List<indexstan> listadb = new List<indexstan>();
            // 加using自动释放数据库连接,避免资源泄漏
            using (FbConnection myConnection = new FbConnection(_connString))
            {
                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();
                using (FbDataReader myReader = myCommand.ExecuteReader())
                {
                    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(listadb.Count);
            return listadb;
        }

        // 私有辅助方法,内部查询库存用
        private double zwr(string myIndex)
        {
            var result = _listadb.FirstOrDefault(x => x.index == myIndex)?.standysp;
            return result ?? -1;
        }

        // 对外暴露的公共方法,就是你需要的返回WynikPorownania列表的接口
        public List<WynikPorownania> PobierzWynikiPorownania()
        {
            List<WynikPorownania> listatf = File.ReadAllLines(_txtPath).Select(line =>
            {
                var linia = line.Split("=");
                string index = linia[0];
                int value = int.Parse(linia[1]);
                if (value < 0)
                {
                    value = 0;
                }
                double stanWMagazynie = zwr(index);
                if (stanWMagazynie == -1)
                {
                    // 这里原来的逻辑是返回-1,你可以根据业务需求改成0或者其他默认值
                    return new WynikPorownania { Indeks = index, Ilosc = (int)stanWMagazynie };
                }
                else
                {
                    return new WynikPorownania { Indeks = index, Ilosc = (int)Math.Max(value, stanWMagazynie) };
                }
            }).ToList();
            return listatf;
        }
    }

    class Program
    {
        public static void Main()
        {
            try
            {
                // 实例化服务,调用公共方法获取结果
                var service = new PorownanieMagazynuService();
                var wyniki = service.PobierzWynikiPorownania();
                
                // 原来的打印逻辑
                foreach (var wynik in wyniki)
                {
                    Console.WriteLine(wynik);
                }
            }
            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);
            }
        }
    }
}

调用说明

其他项目集成时只需要引用当前程序集,按如下方式调用即可:

var service = new dokselect.PorownanieMagazynuService();
List<dokselect.WynikPorownania> wyniki = service.PobierzWynikiPorownania();

你也可以根据需求把数据库连接字符串、txt文件路径改成构造方法的参数,提升灵活性。

内容的提问来源于stack exchange,提问作者shade999

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 20:54:05