如何从不同的文件中引用c#类?
本文关键字:引用 文件 | 更新日期: 2023-09-27 18:19:18
我是编程新手,我正在尝试使用BBEdit的"TextWrangler"程序(类似notepad++,但适用于Mac)的Mono编译器学习c#。然而,我的问题非常简单:我试图在c#中编写一个非常简单的程序,该程序使用来自不同.cs文件的类。
我正在为此挣扎。如果类在同一个。cs文件中,我没有问题;否则,bash终端会一直给我错误。下面是我的代码:
Program.cs:
// Client class, where Main method calls the Car method
using System;
using Auto;
namespace Auto
{
class Program
{
public static void Main(string[] args)
{
//Instantiate car class
Car car = new Car("Toyota", "Corolla", "Sedan", 2014, 25000);
Console.WriteLine(car.Maintenance());
Console.Read();
}
}
}
Car.cs:
// "Car" class (does NOT include the Main method)
using System;
namespace Auto
{
public class Car
{
//Create various attributes for Car Class with getters and setters
public string Make { get; set; }
public int Year { get; set; }
public string Model { get; set; }
public string Type { get; set; }
public int Millage { get; set; }
public DateTime PurchaseDate { get; set; }
//Constructor to instantiate Car object that pass all the necessary attribute values
public Car(string make, string model, string _type, int year, int millage)
{
Make = make;
Model = model;
Type = _type;
Millage = millage;
}
//Maintenance method will check all the inspection that the mechanic has to do based on the millage of the car
public string Maintenance()
{
int index = 1;
string maintenanceList = string.Empty;
if (Millage > 5000)
maintenanceList += (index++).ToString() + ". Oil Change " +Environment.NewLine;
if (Millage > 10000)
{
maintenanceList += (index++).ToString() + ". Check Brakes " + Environment.NewLine;
maintenanceList += (index++).ToString() + ". Rotate Tires " + Environment.NewLine;
maintenanceList += (index++).ToString() + ". Lube Hinges, Lock, and Latches" + Environment.NewLine;
}
if (Millage > 15000)
maintenanceList += (index++).ToString() + ". Replace air Cleaner element" + Environment.NewLine;
if (Millage > 30000)
maintenanceList += (index++).ToString() + ". Replace Dust and Pollen Filter" + Environment.NewLine;
return maintenanceList;
}
}
}
就是这样。代码比看起来简单-但是每当我尝试编译这些文件时,这两个文件都保存在我的Finder中的同一文件夹下,我得到这些结果:
Program.cs:
Compilation failed: 1 error(s), 0 warnings
Program.cs(14,13): error CS0246: The type or namespace name `Car' could not be found. Are you missing an assembly reference?
Program.cs(15,31): error CS0841: A local variable `car' cannot be used before it is declared
Car.cs:
error CS5001: Program `Car.exe' does not contain a static `Main' method suitable for an entry point
所以是的,我被困住了。我已经阅读了很多关于c#入门类构建的资料,但是我的运气没有任何收获。
您在"Program.cs"文件中的错误与此无关。一旦你修复了"Car.cs"文件中的一个,它们就会消失。
- "Car.cs"有错误
- 不编译
- 没有生成DLL
- 编译"Program.cs"文件时找不到
修复一个,另一个也会修复。
问题仍然是:如何修复"Car.cs"中的错误。这肯定是项目文件中的文件属性中的一个问题。
可以在这里找到一些可能的答案,当pixaloop写道:
将Project> Properties下的Output Type更改为"Class Library"的输出类型。默认情况下,此设置可能已设置为"控制台应用程序"。
作为旁注,你应该尝试在MacOS中为你的c#开发MonoDevelop。它将简化您的项目/文件/dll管理