用外部类的对象调用内部类的静态方法

本文关键字:内部类 静态方法 调用 对象 外部 | 更新日期: 2023-09-27 18:06:31

我有两个类。一个是:

namespace DataStructures_Algorithms
{
    public class BackendService
    {
        public class LocationServiceQueue
        {
            private static string deviceId;
            private static POI currentPOI;
            private static DateTime timeStamp;
            private static ConcurrentQueue<DeviceMessage> concurrentQueue = new ConcurrentQueue<DeviceMessage>();
            public static void Enqueue(DeviceMessage deviceMessage)
            {
                try
                {
                    concurrentQueue.Enqueue(deviceMessage);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception Occured in LocationServiceQueue Class " + ex.ToString());
                }
            }
        }
}

,现在我想调用LocationServiceQueue类的enqueue方法。

                backendService.LocationServiceQueue.Enqueue(new DeviceMessage
                {
                    DeviceId = deviceID,
                    CurrentPOI = currentPOI,
                    Timestamp = DateTime.Now
                });

给出一个您无法访问的错误。我如何访问?

用外部类的对象调用内部类的静态方法

Enqueue是一个类方法,所以你必须使用类名访问方法(而不是使用实例变量)。

由于内部LocationServiceQueue类是一个公共类,您可以这样做。

BackendService.LocationServiceQueue.Enqueue(new DeviceMessage
            {
                DeviceId = deviceID,
                CurrentPOI = currentPOI,
                Timestamp = DateTime.Now
            });

我在评论中发布了一个链接,但答案会更容易帮助你。修改代码如下:

namespace DataStructures_Algorithms
{
    public class BackendService
    {
        public class LocationServiceQueue
        {
            private BackendService _backendservice;
            private static string deviceId;
            private static POI currentPOI;
            private static DateTime timeStamp;
            private static ConcurrentQueue<DeviceMessage> concurrentQueue = new ConcurrentQueue<DeviceMessage>();
            public LocationServiceQueue(BackendService outer)
            {
                _backendservice = outer;
            }

            public static void Enqueue(DeviceMessage deviceMessage)
            {
                try
                {
                    concurrentQueue.Enqueue(deviceMessage);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception Occured in LocationServiceQueue Class " + ex.ToString());
                }
            }
        }
}

,后来:

BackendService.LocationServiceQueue l = new BackendService.LocationServiceQueue(new BackendService());

虽然这只适用于当你不关心你的BackendService类,而只关心LocationServiceQueue方法。