C#从private static void访问class'es成员

时间:2014-03-02 23:43:17

标签: c# class static-methods member

我需要同时使用“public int”(不是100%肯定)和“private static void”(100%肯定!)

但是,我无法从私有静态void中访问class'es成员数据。

有人可以告诉我如何解决这个问题或解决它吗?

非常感谢您的帮助!

namespace MyDLL
{

    public class clsDLL
    {
        ThirdPartyAPI _api = new ThirdPartyAPI();
        double _X = 0;

        //My C# project is a COM DLL that will be called by other applications, so I have chosen "public int" here
        public int open(string uKey)
        {
            int iRet = _api.Open(uKey);
            return iRet;
        }

        //This is a callback that will be called by "_api"
        private static void CallBack_MoveDetected(ref MoveData data, IntPtr userData)
        {
            _X=data.positionX; //this does not work. I can not access "_X" from here.
        }

    }
}

1 个答案:

答案 0 :(得分:1)

不确定这是否有意义,但您可以将班级更改为

namespace MyDLL
{
    public class clsDLL
    {
        ThirdPartyAPI _api = new ThirdPartyAPI();
        double _X = 0;

        public double X 
        { 
           get{ return _X;} 
           set{ _X = value;}
        }

        public int open(string uKey)
        {
            int iRet = _api.Open(uKey);
            return iRet;
        }

        private static void CallBack_MoveDetected(ref MoveData data, 
                            IntPtr userData, clsDLL instance)
        {
            instance.X=data.positionX; 
        }
    }
}

回到你最初的问题。如果没有类的实例,静态方法就没有办法直接使用实例变量。想一想。存在静态方法而不需要声明任何实例,如果您尝试以任何方式执行的操作,那么静态方法从哪个实例读取变量_X的值?