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

时间:2016-09-12 01:31:51

标签: c# asp.net

我有两节课。一个是这个:

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

它会出现您无法访问的错误。我该如何访问?

2 个答案:

答案 0 :(得分:1)

Enqueue是一个类方法,因此您必须使用类名访问方法(使用实例变量)。

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

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

答案 1 :(得分:1)

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

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方法。