gpt4 book ai didi

c# - 在非默认结构构造函数中调用结构方法

转载 作者:行者123 更新时间:2023-11-30 19:22:08 24 4
gpt4 key购买 nike

我有一个非常简单的例子,我用它来学习 C# 中的结构:

struct ScreenPosition
{
// These are the two private members of the structure
private int x;
private int y;

private int RangeCheckedX(int xPos)
{
if (xPos < 0 || xPos > 1280)
{
throw new ArgumentOutOfRangeException("X");
}
return xPos;
}

private int RangeCheckedY(int yPos)
{
if (yPos < 0 || yPos > 1024)
{
throw new ArgumentOutOfRangeException("Y");
}
return yPos;
}

// Declaring the non-default constructor
public ScreenPosition(int X, int Y)
{
this.x = RangeCheckedX(X); // ERROR HERE
this.y = RangeCheckedY(Y); // ERROR HERE
}

// Declaring the property X - Follows a syntax. See the C# quick reference sheet
public int X
{
get
{
return this.x;
}

set
{
this.x = RangeCheckedX(value);
}
}
// Declaring the property X - Follows a syntax. See the C# quick reference sheet
public int Y
{
get
{
return this.y;
}

set
{
this.y = RangeCheckedY(value);
}
}
}

我在“ERROR HERE”评论行收到此错误:

The 'this' object cannot be used before all of its fields are assigned to

在非默认构造函数中调用结构体方法给结构体成员赋值是否违法?

最佳答案

您可以将这些方法设为静态并且它会起作用,但是在分配所有字段之前您不能调用非静态方法。

关于c# - 在非默认结构构造函数中调用结构方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1671872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com