C#网站App_code两个类怎么相互调用

clipboard.png
在GoalModel.ashx.cs中想调用f.cs的方法,应该怎么做?
GoalModel.ashx.cs

namespace KeyGoal
{
    public class GoalModel : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string t = HttpContext.Current.Request.Form["t"];

            switch (t)
            {
                case "1":
                    GetInfo();
                    break;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        public string GetInfo()
        {
            //要执行的sql语句select 语句
            try
            {
                string sql = "select * from goal";
                DataTable dt = MySQLHelper.QuerySql(sql);
                string json = f.ToString(dt);
                json = json.Replace("\"", "\\\"");
                context.Response.Write("{\"status\":\"" + json + "\"}");
            }
            catch (Exception e)
            {
                throw e;
            }


        }

    }
}

f.cs

namespace KeyGoal
{
    public static class f
    {

public static string ToJson(this DataTable dt)
        {
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();

            javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
            ArrayList arrayList = new ArrayList();
            foreach (DataRow dataRow in dt.Rows)
            {
                Dictionary<string, object> dictionary = new Dictionary<string, object>();  //实例化一个参数集合
                foreach (DataColumn dataColumn in dt.Columns)
                {
                    dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToString());
                }
                arrayList.Add(dictionary); //ArrayList集合中添加键值
            }

            return "{root:" + javaScriptSerializer.Serialize(arrayList) + "}";  //返回一个json字符串
        }
        }
        }
阅读 2.1k
1 个回答

扩展方法,相同的命名空间下,对象直接调用即可。


DataTable dt = MySQLHelper.QuerySql(sql);
var json = dt.ToJson();

扩展方法

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进