我在容器上编写代码,该容器从文本文件接收输入并将其值分配给适当的变量。 这里出现了错误 访问非静态成员需要一个对象引用`GetContainerDetails.Containerdetails.cnum请解决此问题。
using System;
using System.IO;
namespace GetContainerDetails
{
class Containerdetails
{
private string cnum;
private double length;
private double height;
private double depth;
private double volume;
// Declare a number of box of type string:
public string containernum
{
get { return cnum; }
set { cnum = value; }
}
// Declare properties of box of type double:
public double conlength
{
get { return length; }
set { length = value; }
}
public double conheight
{
get { return height; }
set { height = value; }
}
public double condepth
{
get { return depth; }
set { depth = value; }
}
public double convolume
{
get { return volume; }
set { volume = value; }
}
static void Main(string[] args)
{
try
{
using (StreamReader sr = new StreamReader("c:/containervalues.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] Parts = line.Split(' ');
cnum=Parts[0];
length=Convert.ToDouble(Parts[1]);
height=Convert.ToDouble(Parts[2]);
depth=Convert.ToDouble(Parts[3]);
volume = Convert.ToDouble(Parts[4]);
}
}
}
catch (Exception ex)
{
// what failed?
}
}
}
}
答案 0 :(得分:0)
方法static void Main
无法访问非静态成员cnum, length, height, depth and volume
使方法非静态或使成员静态。
答案 1 :(得分:0)
您的字段不是静态的。您正尝试从静态方法设置它们。要么将它们设置为静态,要么创建Containerdetails
的实例并使用其属性。我想你需要后者:
// create list of containers
List<Containerdetails> containers = new List<Containerdetails>();
using (StreamReader sr = new StreamReader("c:/containervalues.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
// create new instance of container for each line in file
Containerdetails container = new Containerdetails();
string[] Parts = line.Split(' ');
// set non-static properties of container
container.cocnum = Parts[0];
container.colength = Convert.ToDouble(Parts[1]);
container.coheight = Convert.ToDouble(Parts[2]);
container.codepth = Convert.ToDouble(Parts[3]);
container.covolume = Convert.ToDouble(Parts[4]);
// add container to list of containers
containers.Add(container);
}
}
附注 - 如果应用程序中只有一个容器,请考虑使用应用程序设置来保存App.config文件中的应用程序设置:
<appSettings>
<add key="num" value="1"/>
<add key="length" value="12.5"/>
<add key="height" value="3.5"/>
<add key="depth" value="10"/>
<add key="volume" value="60.75"/>
</appSettings>
支持更容易,然后白色空格分隔数字。轻松获取应用程序设置
double depth = Double.Parse(ConfigurationManager.AppSettings["depth"]);