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

如何将创建列表的代码移至独立类并调用(C#/ASP.NET)

解决方案

一、先解决App_Code类无法引用的问题

1. 调整类的命名空间

把Class1的命名空间从FootballResultPredictor.App_Code改为FootballResultPredictor,避免嵌套命名空间导致引用麻烦:

using System;

namespace FootballResultPredictor
{
    public class Class1
    {
        public static string MyMethod()
        {
            return "test";
        }
    }
}

2. 确保类文件的编译属性

右键App_Code文件夹中的Class1.cs → 选择「属性」→ 确认「生成操作」设置为「编译」。

3. 在页面中引用命名空间并调用

  • 后台代码(StartNewSeason.aspx.cs):
    添加命名空间引用后直接调用静态方法:
    using FootballResultPredictor;
    
    public partial class StartNewSeason : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string testStr = Class1.MyMethod();
            // 自行处理返回值
        }
    }
    
  • 前端aspx页面:
    在页面顶部导入命名空间,再在代码块中调用:
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="StartNewSeason.aspx.cs" Inherits="StartNewSeason" %>
    <%@ Import Namespace="FootballResultPredictor" %>
    
    <!DOCTYPE html>
    <html>
    <body>
        <%= Class1.MyMethod() %>
    </body>
    </html>
    

二、编写独立的球队列表类

1. 创建球队数据类

在App_Code文件夹中新建TeamData.cs,用静态类封装球队列表(两种实现方式选其一即可):

using System.Collections.Generic;

namespace FootballResultPredictor
{
    public static class TeamData
    {
        // 方式1:静态方法,每次调用返回新列表
        public static List<string> GetFootballTeams()
        {
            return new List<string>
            {
                "Arsenal",
                "Aston Villa",
                "Bournemouth",
                "Brentford",
                "Brighton & Hove Albion",
                "Chelsea"
            };
        }

        // 方式2:只读静态属性,仅初始化一次(性能更优)
        public static readonly List<string> FootballTeams = new List<string>
        {
            "Arsenal",
            "Aston Villa",
            "Bournemouth",
            "Brentford",
            "Brighton & Hove Albion",
            "Chelsea"
        };
    }
}

2. 在其他类/页面中调用

  • 后台代码调用:
    using FootballResultPredictor;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        // 调用静态方法
        var teamsFromMethod = TeamData.GetFootballTeams();
        // 或直接使用静态属性
        var teamsFromProperty = TeamData.FootballTeams;
    
        // 示例:绑定到下拉控件
        ddlTeams.DataSource = teamsFromProperty;
        ddlTeams.DataBind();
    }
    
  • 前端页面调用:
    <%@ Import Namespace="FootballResultPredictor" %>
    
    <ul>
        <% foreach (var team in TeamData.FootballTeams) { %>
            <li><%= team %></li>
        <% } %>
    </ul>
    

补充说明

如果你的项目是ASP.NET Web Application(而非Web Site),无需依赖App_Code文件夹,直接将类文件放在项目根目录或自定义文件夹中即可,命名空间配置和调用方式完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:55:23