如何在C#中检测变量更改并获取变量的值

时间:2019-01-10 06:56:08

标签: c#

我尝试使用property changed event来为bool值分配一个值,以获取连接状态。

但是,我想从另一个类中侦听变量的这种变化并执行一些操作。如何在C#中实现这一目标?

private bool isDisconnected;

public bool IsDisconnected
{
    get { return isDisconnected; }
    set
    {
        isDisconnected = value;
        OnPropertyChanged("IsDisconnected");
    }

}

public event PropertyChangedEventHandler PropertyChanged;

public override void OnConnectionStateChange(BluetoothGatt gatt, [GeneratedEnum] GattStatus status, [GeneratedEnum] ProfileState newState)
{
    base.OnConnectionStateChange(gatt, status, newState);

    if(newState == ProfileState.Connected)
    {
        isDisconnected = true;
        gatt.DiscoverServices();
    }

    else if(newState == ProfileState.Disconnected)
    {
        gatt.Close();
        isDisconnected = true;
        Log.Info("BLE", "Status: Disconnected");
    }

}

在另一个基本上是Service的类中,我想听变量IsDisconnected。请有人帮我。

我的服务类别:

[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
    try
    {
        Toast.MakeText(this, "Background service started", ToastLength.Long);
        t = new Thread(() =>
        {
            Task.Run(async () =>
            {
                ConnectionListener gatt = new ConnectionListener ();
                gatt.PropertyChanged += (s, e) =>
                {
                    if (e.PropertyName == nameof(GattCallback.IsDisconnected))
                    {

                    }
                };

            });
        });

        t.Start();
    }
}

1 个答案:

答案 0 :(得分:3)

假设您的类的实例称为connection。然后从另一个类中连接PropertyChanged事件:

connection.PropertyChanged += (s,e) =>
{
   if (e.PropertyName == nameof(YourClass.IsDisconnected))
   { 
       //isDisconnected changed, perform your logic
   }
}

当然,这只是示例代码,如果两个实例的生存期不同,则将事件处理移至一个方法将是适当的。这样,您以后就可以取消订阅该事件,这样就不会引起内存泄漏。

此外,您需要更新GattCallback类以设置IsDisconnected属性,而不是isDisconnected方法中的OnConnectionChange字段:

if(newState == ProfileState.Connected)
{
    IsDisconnected = false; //notice change true -> false
    gatt.DiscoverServices();
}

else if(newState == ProfileState.Disconnected)
{
    gatt.Close();
    IsDisconnected = true;
    Log.Info("BLE", "Status: Disconnected");
}

似乎那里也有一个错误-在两种情况下,您都将IsDisconnected设置为true,这可能不是您想要的。