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

C#跨.cs文件访问List并统计输出:解决LIST_ONE不存在错误

跨文件访问List并输出内容的问题解决

错误根源

LIST_ONE是MY_LISTS.MY_LIST.GET_LISTS()方法内的局部变量,作用域仅限该方法内部,因此Program.cs的Main方法无法直接访问它,导致编译错误:"The name 'LIST_ONE' does not exist in the current context"。

修改后的完整代码

Class.cs(无需改动)

namespace CLASSES{
    public class ITEM{
        public string Name {get;set;}
        public string Location {get;set;}

        public ITEM(string Name, string Location){
            this.Name = Name;
            this.Location = Location;
        }
    }
}

List.cs(修改方法返回列表)

using CLASSES;
using System.Collections.Generic;

namespace MY_LISTS{
    public class MY_LIST{
        // 修改返回类型为List<ITEM>,返回创建好的列表
        public static List<ITEM> GET_LISTS(){
            List<ITEM> LIST_ONE = new List<ITEM>();
            var List_Item_1 = new ITEM("Test Name", "Test Location"); 
            LIST_ONE.Add(List_Item_1);
            return LIST_ONE;
        }
    }
}

Program.cs(引入命名空间、获取列表并修复循环)

using CLASSES;
using MY_LISTS;
using System;

namespace MYCODE{
    class Program{
        static void Main(string[] args){
            // 调用方法获取列表实例
            var listOne = MY_LIST.GET_LISTS();

            // 修复索引越界问题:List索引从0开始,循环条件改为i < listOne.Count
            for(int i = 0; i < listOne.Count; i++){
                if(listOne[i].Location == "Test Location"){
                    Console.WriteLine($"LIST_ONE has an item named: {listOne[i].Name} with a location of: {listOne[i].Location}");
                }
            }

            // 更简洁的foreach遍历方式(推荐)
            foreach(var item in listOne){
                if(item.Location == "Test Location"){
                    Console.WriteLine($"LIST_ONE has an item named: {item.Name} with a location of: {item.Location}");
                }
            }
        }
    }
}

关键注意事项

  1. 作用域与返回值:通过让GET_LISTS方法返回列表实例,让外部代码能获取到原本仅在方法内部存在的List。
  2. 命名空间引用:Program.cs必须引入MY_LISTS命名空间,才能访问MY_LIST类及其静态方法。
  3. 索引规则:C#集合的索引从0开始,原代码的i <= LIST_ONE.Count会触发索引越界异常,需改为i < listOne.Count。
  4. 项目文件包含:确保VSCode中的.csproj文件包含所有.cs文件,示例配置如下:
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <Compile Include="MAIN\Program.cs" />
    <Compile Include="C#_ASSETS\Class.cs" />
    <Compile Include="C#_ASSETS\List.cs" />
  </ItemGroup>
</Project>

内容的提问来源于stack exchange,提问作者Self Taught C Sharp

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:51:28