我一直在做一个家庭项目,但是遇到了一个问题,我错过了解决方案。
我创建了以下课程
public class Sides
{
//These are the encapsulated data
private int intAdj; //adjacent
private int intOpp; //opposite
private Double doubleHypot; //hypotenuse
//This is the constructor
public Sides(int intAdj, int intOpp, Double doubleHypot)
{
//less confusion when the same name is used
this.intAdj = intAdj;
this.intOpp = intOpp;
this.doubleHypot = doubleHypot;
}
//Getters and Setters
public int IntAdj { get; set; }
public int IntOpp { get; set; }
public Double DoubleHypot { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我从这个方法调用它
Sides mySide;
//This is where the calculations occur
for (int indexAdj = 1; indexAdj < (intTriangleSize + 1); indexAdj++)
{
for (int indexOpp = 1; indexOpp < (intTriangleSize + 1); indexOpp++)
{
doubleHypotenuse = doubHypot(doubleSquare(indexAdj), doubleSquare(indexOpp));
mySide = new Sides(indexAdj, indexOpp, doubleHypotenuse);
MessageBox.Show("Green Lantern" + "\n"
+ "Adjacent " + indexAdj + "\n"
+ "Opposite " + indexOpp + "\n"
+ "Hypotenuse " + doubleHypotenuse);
listTriangle.Add(mySide);
}
}
Run Code Online (Sandbox Code Playgroud)
列表的声明和初始化如下
private List<Sides> listTriangle;
listTriangle = new List<Sides>();
Run Code Online (Sandbox Code Playgroud)
经过反复试验,应该正确地填写列表中的值,如您在此处所附图像中所见

然后,我立即尝试通过循环遍历循环以检查是否正常工作,从而通过此代码检查列表。该代码是
for (int indexRan = 0; indexRan < listTriangle.Count; indexRan++)
{
if (indexRan == 2)
{
MessageBox.Show(listTriangle[2].IntAdj + " Purple Haze");
}
}
Run Code Online (Sandbox Code Playgroud)
我将不胜感激,并感谢任何帮助和指导
问题是您要分配给构造函数中的私有字段,而不是要从调用方访问的公共属性。
避免这种情况的一种方法是仅使用公共属性:
public class Sides
{
// Public properties
public int Adjacent { get; set; }
public int Opposite { get; set; }
public double Hypotenuse { get; set; }
// Constructor
public Sides(int adjacent, int opposite, double hypotenuse)
{
this.Adjacent = adjacent;
this.Opposite = opposite;
this.Hypotenuse = hypotenuse;
}
}
Run Code Online (Sandbox Code Playgroud)
如果只允许在类本身中设置属性,则可以使用setter private:
public class Sides
{
// Public read-only properties
public int Adjacent { get; private set; }
public int Opposite { get; private set; }
public double Hypotenuse { get; private set; }
// Constructor
public Sides(int adjacent, int opposite, double hypotenuse)
{
this.Adjacent = adjacent;
this.Opposite = opposite;
this.Hypotenuse = hypotenuse;
}
}
Run Code Online (Sandbox Code Playgroud)
另请注意,不必type在变量名称中包含。