簡體   English   中英

C#錯誤:非靜態字段,方法或屬性需要對象引用

[英]C# Error: Object reference is required for the non-static field, method, or property

我需要一點幫助。 我試圖在我的WPF應用程序中填充緯度和經度值2個textboxes 現在,我可以將值顯示在MessageBox並以所需的格式設置它們在文本框中的顯示方式。

但是,當我嘗試將數據發送到文本框時,

“非靜態字段,方法或屬性'Registration.tbXCoords'需要對象引用。

任何幫助將不勝感激。

//Registration.xaml.cs     

using System.Windows;
using System.Device.Location;
using System;

namespace Battle_Sample
{

public partial class Registration : Window
{
    public Registration()
    {
        WindowStartupLocation = WindowStartupLocation.CenterScreen;
        InitializeComponent();
        CLocation myLocation = new CLocation();
        myLocation.GetLocationEvent();
    }

    public class CLocation
    {
        GeoCoordinateWatcher watcher;

        public void GetLocationEvent()
        {
            this.watcher = new GeoCoordinateWatcher();
            this.watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
            bool started = this.watcher.TryStart(false, TimeSpan.FromMilliseconds(1000));
            if (!started)
            {
                MessageBox.Show("GeoCoordinateWatcher timed out on start.");
            }
        }

        public void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            PrintPosition(e.Position.Location.Latitude, e.Position.Location.Longitude);
        }

        public void PrintPosition(double Latitude, double Longitude)
        {
            MessageBox.Show("X: " + Latitude.ToString("0.00") + ", Y: " + Longitude.ToString("0.00"));

            //The following two lines are where I am getting the error
            tbXCoords.Text = (Latitude.ToString());
            tbYCoords.Text = (Longitude.ToString());
        }
    }
  }
}




//Registration.xaml

<Window x:Class="Battle_Sample.Registration"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Battle_Sample"
    mc:Ignorable="d"
    Title="Battle Registration" Height="300" Width="300">

<Grid>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="4*"/>
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>

    <StackPanel Grid.Column="0" Grid.Row="3">
        <TextBlock FontWeight="Bold" Text="Location:" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,6,0,0" />
    </StackPanel>

    <StackPanel Orientation="Horizontal" Grid.Column="1" Grid.Row="3">
        <TextBlock Margin="2" VerticalAlignment="Center">X</TextBlock>
        <TextBox x:Name="tbXCoords" Margin="5" Width="50" IsEnabled="False" />
    </StackPanel>

    <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="3">
        <TextBlock Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center">Y</TextBlock>
        <TextBox x:Name="tbYCoords" Margin="5" Width="50" IsEnabled="False" />
    </StackPanel>
</Grid>

tbXCoordstbYCoords是您的Registration類中定義的字段,並且由於錯誤消息告訴您,它們不是靜態的,因此要訪問它們,您需要指定對“擁有”它們的Registration對象的實際引用。

實際上,您正在做的事情等同於:

public class A
{
    public string Hello = "Hello";

    public class B
    {
        //Hello of what A?
        public void SayHello() { 
            Console.Write(Hello); } //Error  
    }
}

這顯然是錯誤的。 您需要做的是:

public class B
{
    //Specify what specific A's Hello you want.
    public void SayHello(/*A a*/) {
        Console.Write(a.Hello); }   
}

a可以是局部變量,字段,方法參數,屬性等,但它必須是指向具體A對象的變量(或空引用,在這種情況下,您的代碼將編譯但在運行時失敗)。

為了完全理解您收到的錯誤消息,請考慮Hello靜態的情況:

public class A
{
    public static string Hello = "Hello";

    public class B
    {
        public void SayHello() { 
            Console.Write(Hello); }  
    }
}

現在,因為該領域這段代碼編譯就好Hello現在是“擁有”的類型A通過具體實例本身,而不是A ; 對於所有A來說,只有一個Hello (這是對靜態字段的真正非正式描述,但是應該能對整個靜態圖片有一個合理的認識)。

好吧,足夠聊天了,您如何解決呢? 好吧,在不了解太多代碼的情況下,一種合理的方法是通過構造函數告訴具體的CLocation實例具體的Registration擁有它:

public Registration()
{
    WindowStartupLocation = WindowStartupLocation.CenterScreen;
    InitializeComponent();
    CLocation myLocation = new CLocation(this);
    myLocation.GetLocationEvent();
}

public class CLocation
{
     private readonly Registration registrationWindow;

     public CLocation(Registration registrationWindow) {
         this.registrationWindow = registrationWindow; }

     //...

    public void PrintPosition(double Latitude, double Longitude)
    {
        //...
        registrationWindow.tbXCoords.Text = (Latitude.ToString());
        registrationWindow.tbYCoords.Text = (Longitude.ToString());
    }
}

現在,如果僅在PrintPosition方法中需要引用,則這可能是一個PrintPosition 在這種情況下,您可以考慮將具體的窗口實例指定為參數:

public void PrintPosition(Registration registrationWindow,
                          double Latitude, 
                          double Longitude)
{
    //...
    registrationWindow.tbXCoords.Text = (Latitude.ToString());
    registrationWindow.tbYCoords.Text = (Longitude.ToString());
}

同樣,您應該知道哪種方法更適合您的特定情況。

我不知道您為什么要在不同的類中放入“ GeoLocation”代碼。 但是您可以使用事件來解決此問題:

public partial class Registration: Window
{
    public Registration()
    {
        InitializeComponent();
        WindowStartupLocation = WindowStartupLocation.CenterScreen;
        InitializeComponent();
        CLocation myLocation = new CLocation();
        myLocation.OnPositionChanged += new EventHandler<PositionEventArgs>(myLocation_OnPositionChanged);
        myLocation.GetLocationEvent();

    }

    private void myLocation_OnPositionChanged(object sender, PositionEventArgs e)
    {
        tbXCoords.Text = (e.Latitude.ToString());
        tbYCoords.Text = (e.Longitude.ToString());
    }

    public class CLocation
    {
        public EventHandler<PositionEventArgs> OnPositionChanged;
        GeoCoordinateWatcher watcher;

        public void GetLocationEvent()
        {
            watcher = new GeoCoordinateWatcher();
            watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
            bool started = this.watcher.TryStart(false, TimeSpan.FromMilliseconds(1000));
            if (!started)
            {
                MessageBox.Show("GeoCoordinateWatcher timed out on start.");
            }
        }

        public void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            OnPositionChanged?.Invoke(this, new PositionEventArgs() { Latitude = e.Position.Location.Latitude, Longitude = e.Position.Location.Longitude });
        }
    }
}

這是PostionEventArgs類:

public class PositionEventArgs
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM