C# ApiController访问值文本框Windows窗体
我正在用webapi在Windows窗体中做一个项目。当从webapi调用时,我会得到一个文本框的值 下面是代码片段,但它不起作用,因为它在代码后面给出了错误C# ApiController访问值文本框Windows窗体,c#,asp.net,winforms,C#,Asp.net,Winforms,我正在用webapi在Windows窗体中做一个项目。当从webapi调用时,我会得到一个文本框的值 下面是代码片段,但它不起作用,因为它在代码后面给出了错误 namespace TCCWindows { public partial class FormPrincipal : Form { public static string PegarCoordenadas() { return edtLatitudeGMS.
namespace TCCWindows
{
public partial class FormPrincipal : Form
{
public static string PegarCoordenadas()
{
return edtLatitudeGMS.Text + " | " + edtlngGMS.Text;
}
}
public class GPSController : ApiController
{
public string Posicao()
{
return TCCWindows.FormPrincipal.PegarCoordenadas();
}
}
}
错误:
Error 2 An object reference is required for the non-static field, method, or property 'TCCWindows.FormPrincipal.edtLatitudeGMS' I:\C#\TCC\TCCWindows\FormPrincipal.cs 224 20 TCCWindows
Error 3 An object reference is required for the non-static field, method, or property 'TCCWindows.FormPrincipal.edtlngGMS' I:\C#\TCC\TCCWindows\FormPrincipal.cs 224 50 TCCWindows
您的PegarCoordenadas方法是静态的,但是像edtratitudegms这样的控件属于表单的某个实例。静态方法中引用的所有内容本身都需要是静态的。所以你的代码无效 当您将PegarCoordenadas设置为静态时,因为您当时没有对FormPrincipal实例的具体引用,如果您想调用它,那么解决这个问题的方向就错了。你必须具体提到这样一个例子。创建FormPrincipal时,请将引用存储在某个位置(可能在GPSController中),并使其在Posicao方法中可访问。以下是我的解决方案:
public partial class FormPrincipal : Form
{
public static string PegarCoordenadas()
{
return LatitudeGMS + " | " + LongGMS;
}
public static string LatitudeGMS, LongGMS;
public FormPrincipal(){
InitializeComponents();
edtLatitudeGMS.TextChanged += (s,e) => { LatitudeGMS = edtLatitudeGMS.Text;};
edtlngGMS.TextChanged += (s,e) => {LongGMS = edtlngGMS.Text;};
}
}
您只能在静态方法中使用
静态内容。您希望发生什么?表单在哪里实例化?