我是C#的入门者, 我想在主类中创建一个新对象, 我该怎么办?
House.cs
namespace Assignment
{
public class House
{
//the class containing properties of the house
//Properties with their GETTERS AND SETTERS
public int housenumber
{
get { return this.housenumber; }
set { this.housenumber = value; } // Setter declaration
}
public string color
{
get { return this.color; }
set { this.color = value; }
}
public string nationality
{
get { return this.nationality; }
set { this.nationality = value; }
}
public string drink
{
get { return this.drink; }
set { this.drink = value; }
}
public string cigarrette
{
get { return this.cigarrette; }
set { this.cigarrette = value; }
}
public string pet
{
get { return this.pet; }
set { this.pet = value; }
}
public House( )
{
}
}
}
但是在下面编译我的主类时,我收到错误CS0246 “找不到类型或名称空间名称'House'(您是否缺少using指令或程序集引用?)
Solver.cs
using System;
namespace Assignment
{
public class solver{
// the main class
static void Main()
{
House myhouse = new House();
}
}
}
............................................... ............................................................. ................................
答案 0 :(得分:0)
属性是功能类的成员,本身不能存储任何数据。因此,您必须声明字段以存储属性数据:
private string color;
public string Color
{
get { return color; }
set { color = value; }
}
但是在简单的情况下,我们可以声明属性而无需显式声明字段:
int Color { get; set; }
.NET编译器将创建“隐藏”且不可见的字段来存储此属性的数据。
答案 1 :(得分:0)
首先,将具有大量属性的文件“ House.cs ”中的“房屋”类。
1)注意属性名称的命名规则冲突。这些单词 应该 以大写字母开头。 (饮料=>饮料)。
2)您可以使用表达式主体为属性清除代码。
3)可以删除一个空的构造函数。 现在您的课程是:
public class House
{
/* Useless constructor. You can remove this.
public House() { }
*/
public int HouseNumber { get; set; } // Expression body with no violations in the name
public string Color { get; set; }
public string Nationality { get; set; }
public string Drink { get; set; }
public string Cigarrette { get; set; }
public string Pet { get; set; }
}
要实例化对象并使用它并设置值,可以执行以下操作:
using Assignment; // Use this to import your class
using System;
namespace ConsoleApp1 {
class Program {
static void Main() {
// You can instantiate like this
var house = new House();
house.Nationality = "French"; // Unique value assignation using house
// If you want to set a lot of values for your house object do this:
var myHouse = new House {
Cigarrette = "Camel" ,
Color = "Yellow",
Nationality = "French"
};
// Now you have access to the House's properties ( if you use the using ).
Console.WriteLine( house.Nationality ); // French
Console.WriteLine( myHouse.Nationality ); // French
}
}
}
是的,您必须使用using Assignment
导入“ House.cs ”
如果由于类House.cs在另一个项目中而无法使用,则可以执行以下操作:
右键单击主项目->添加参考->将House.cs添加到项目中