我正在构建一个简单的类,它允许我计算一个类的房间尺寸,但我无法让代码正常工作。当我运行它时,这些是我收到的错误。
/p1/room.cs(1,7):错误CS0116:命名空间不能直接包含字段或方法等成员
如果有意隐藏,请使用new关键字。
/p1/room.cs(1,1):错误CS0246:找不到类型或命名空间名称' using‘(是否缺少using指令或程序集引用?)
我做了一些研究,发现上面的两个错误似乎大多数时候都指向不匹配的括号,但在搜索我的room.cs文件后,我无法找到任何一个。在将我的文件的头文件与其他类进行比较时,我发现我找不到任何差异。
这是我的room.cs文件
Using System;
namespace p1
{
public class Room
{
private string type;
private double length;
private double width;
private double height;
public Room()
{
type = "Default";
length = 0.0;
width = 0.0;
height = 0.0;
}
public Room(string t, double l, double w, double h)
{
type = t;
length = l;
width = w;
height = h;
}
public void SetType(string t)
{
type = t;
}
public void SetLength(double l)
{
length = l;
}
public void SetWidth(double w)
{
width = w;
}
public void SetHeight(double h)
{
height = h;
}
public string GetType()
{
return type;
}
public double GetLength()
{
return length;
}
public double GetWidth()
{
return width;
}
public double GetHeight()
{
return height;
}
public double GetArea()
{
return length*width;
}
public double GetVolume()
{
return length*width*height;
}
public void Display()
{
Console.WriteLine("Room Type: " + this.GetType());
Console.WriteLine("Room Length: " + this.GetLength());
Console.WriteLine("Room Width: " + this.GetWidth());
Console.WriteLine("Room Height: " + this.GetHeight());
Console.WriteLine("Room Area: " + this.GetArea().ToString("F 2") + " sq ft " );
Console.WriteLine("Room Volume: " + this.GetVolume().ToString("F 2") + " cu ft ");
}
}
}如果需要,我也可以发布program.cs文件,但是这个文件太长了,我不想让它不可读。
发布于 2016-10-22 00:55:39
使用NameSpace的正确语法应该是使用而不是使用
用using System;替换Using System;
使用
public new string GetType()
{
return type;
}代替消除警告"Use new keyword is hiding“
public string GetType()
{
return type;
}发布于 2016-10-22 01:15:42
除了vivek nuna已经说过的,你应该习惯C#的属性概念,这将使你的代码不那么冗长,并避免隐藏GetType()的特定问题:
public class Room
{
public string Type { get; set; } = "Default"; // with C#6 property initialization
public double Length { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public Room() {} // no code here, Type is initalized, double is 0 by default
public Room(string t, double l, double w, double h)
{
Type = t;
Length = l;
Width = w;
Height = h;
}
public double GetArea()
{
return Length * Width;
}
public double GetVolume()
{
return Length * Width * Height;
}
public void Display()
{
Console.WriteLine("Room Type: " + Type);
Console.WriteLine("Room Length: " + Length);
Console.WriteLine("Room Width: " + Width);
Console.WriteLine("Room Height: " + Height);
Console.WriteLine("Room Area: " + GetArea().ToString("F 2") + " sq ft " );
Console.WriteLine("Room Volume: " + GetVolume().ToString("F 2") + " cu ft ");
}
}从外部,您现在可以简单地访问属性:
Room r = new Room();
r.Height = 12;
Console.WriteLine(r.Height);编译器完成您在代码中自己完成的所有工作。它为每个属性以及getter和setter方法创建支持字段。你不需要这样做,你可以专注于真正的工作。
https://stackoverflow.com/questions/40181850
复制相似问题