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]
解决方案 »
- C#新手 结构体中嵌套枚举后输出问题
- 关于ImageList 的问题
- 用C#取单精度数组中的最小值时出错。。。大侠帮帮忙吧。
- 请问一下大家怎么实现那个钟的转动
- .Net里能不能直接从FTP上的XML数据读出来,而不要下载到本地再读取,
- C#与Delphi开发CS结构软件
- C#中值类型有“预定义类型”这是什么意思啊?我是新手!急救!
- 图表控件
- 我已经安装了MDAC_TYP.EXE微软提供的2.8板本,现在我想找到microsoft.data.odbc.dll,不知道在什么目录
- 为何我对System.Runtime.Remoting.Channels.TCP的引用失败?
- 几点问题的求解答
- 请问,窗体show之后,还可以设置其owner属性吗
比如:
class example{
private example(){}
public static string a(){return "a ";}
public static string b(){return "b ";}
}
这个类不能被实例化,它暴露了两个static方法供使用。所以你必须加上static
this.x = this.rangeCheckedX(x);
由于编译器不能确定rangeCheckedX是否用到了任何实例成员(这时候某些实例成员可能还没有初始化),因此报错。
该例子中的static用的比较恰当,因为它没有依赖于任何任何实例成员。
如果要去掉static,或者正好要调用成员函数,可以调用结构的默认构造(默认构造保证实例成员初始化):
public ScreenPosition(int x, int y) : this()
{
this.x = rangeCheckedX(x);
}
但是你现在用的是结构 ScreenPosition
{
}或者写
public ScreenPosition(int x, int y)
{
this.x = x;
}这样都无法通过编译,因为你写了构造函数,但是你没有为所有字段都完整地赋值。
2:在struct所有字段成员初始化后之前,是不能引用该对象的
我们需要在自定义的构造器中完成所有的字段的初始化操作
这样写:
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;
}
这样看上去有点丑。可以按照#3楼的做法,调用this()。
this.y = 0;
this.x = this.rangeCheckedX(x);
this.y = this.rangeCheckedY(y);