我正在制作一个新的网络服务,以.csv文件的形式翻译短缩短词典中的作品。
网络表单的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
private Dictionary<string, string> _dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
protected void Page_Load(object sender, EventArgs e)
{
using (var reader = new StreamReader(File.OpenRead(@"C:/dictionary.csv")))
{
while (!reader.EndOfStream)
{
string[] tokens = reader.ReadLine().Split(';');
_dictionary[tokens[0]] = tokens[1];
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
localhost.Service obj = new localhost.Service();
TextBox1.Text = (obj.Translate());
}
}
Web服务的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
public Service() { }
[WebMethod]
public string Translate(string input)
{
string output;
if (_dictionary.TryGetValue(input, out output))
return output;
throw new Exception("Invalid input, please try again.");
}
}
我收到错误:'当前上下文中不存在名称'_dictionary',即使我已创建字符串并作出引用。有什么建议为什么会这样?
答案 0 :(得分:2)
_dictionary
是_Default
班级的成员,而不是Service
班级的成员。
正如Marvin Smit在评论中建议的那样,将_dictionary
声明移至Service
类,将当前位于_Default's
Page_Load
的初始化代码移至Service
上的构造函数1}}。