日期:2014-05-18  浏览次数:20767 次

大虾们 帮看看static 这是为什么??
C# code

    class Program
    {
        static void Main(string[] args)
        {
            ScreenPosition sp = new ScreenPosition(100,23);
            //sp.X = -100;
            //sp.Y = 23;

            //sp.SetX(100);
            //Console.WriteLine(sp.GetX());
            //sp.X = 100;
        }
    }

    struct ScreenPosition
    {
        private int x;
        private int y;

        public ScreenPosition(int x, int y)
        {
            this.x = rangeCheckedX(x);
            this.y = rangeCheckedY(y);
        }
        private static int rangeCheckedX(int x)
        {
            if (x < 0 || x > 1280)
            {
                throw new ArgumentOutOfRangeException("X");
            }
            return x;
        }
        private static int rangeCheckedY(int y)
        {
            if (y < 0 || y > 1024)
            {
                throw new ArgumentOutOfRangeException("Y");
            }
            return y;
        }
    }
}




[b]为什么把rangeCheckedX 或者rangeCheckedY 去掉static变成非静态的时候就提示:错误 1 在给“this”对象的所有字段赋值之前,无法使用该对象 G:\code\code\Program.cs 30 22 ScrenPositioon[/b]


------解决方案--------------------
static不能在 实例 中被调用,通常是由某个类来暴露的。
比如:
class example{
private example(){}
public static string a(){return "a ";}
public static string b(){return "b ";}
}
这个类不能被实例化,它暴露了两个static方法供使用。

所以你必须加上static
------解决方案--------------------
如果去掉static,那么构造函数中命令实际上为:
this.x = this.rangeCheckedX(x);
由于编译器不能确定rangeCheckedX是否用到了任何实例成员(这时候某些实例成员可能还没有初始化),因此报错。


该例子中的static用的比较恰当,因为它没有依赖于任何任何实例成员。
如果要去掉static,或者正好要调用成员函数,可以调用结构的默认构造(默认构造保证实例成员初始化):
public ScreenPosition(int x, int y) : this()
{
this.x = rangeCheckedX(x);
}

------解决方案--------------------
1:由于struct是值类型,所以它和class有些不同
2:在struct所有字段成员初始化后之前,是不能引用该对象的
我们需要在自定义的构造器中完成所有的字段的初始化操作
这样写:
C# code


public ScreenPosition(int x, int y)
        {
            this.x = x;          //这里是关键
               this.y = y;          //这里是关键
               this.x = this.rangeCheckedX(x);
            this.y = this.rangeCheckedY(y);
        }
        private  int rangeCheckedX(int x)
        {
            if (x < 0 || x > 1280)
            {
                throw new ArgumentOutOfRangeException("X");
            }
            return x;
        }
        private  int rangeCheckedY(int y)
        {
            if (y < 0 || y > 1024)
            {
                throw new ArgumentOutOfRangeException("Y");
            }
            return y;
        }

------解决方案--------------------
其实这样可能美一点
C# code
this.x = 0; 
this.y = 0; 
this.x = this.rangeCheckedX(x);
this.y = this.rangeCheckedY(y);