0

I'm doing a project in Windows Forms with webapi. I would get a value of a textBox when the call is made from webapi.

Below is the code snippet, but it does not work as it gives the error after the code.

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:

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
4

2 回答 2

1

这是我的解决方案:

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;};
    }
}

您只能static stuff在静态方法中使用。

于 2013-06-09T20:14:59.760 回答
1

您的 PegarCoordenadas 方法是静态的,但像 edtLatitudeGMS 这样的控件属于表单的某个实例。您在静态方法中引用的所有内容本身都必须是静态的。所以你的代码无效。

当您将 PegarCoordenadas 设为静态时,因为您在现场没有对 FormPrincipal 实例的具体引用,如果您想调用它,那么您采取了错误的方向来解决这个问题。您必须对此类实例有具体的参考。当您创建 FormPrincipal 时,将引用存储在某处(可能在您的 GPSController 中)并使其可在 Posicao 方法中访问。

于 2013-06-09T19:35:24.533 回答