我正在努力从命令行编译我的 C# 项目。我制作了 2 个简单的类来解决这个问题。我有一个 Person
类和 Registry
存储 Person 数组的类。当我尝试使用 csc 编译注册表文件时,我得到“Registry.cs(4,5): error CS0246: The type or namespace name 'Person' could not be found (are you missing a using directive or an assembly reference?)
”
一段时间后我发现一个笨拙的解决方法是编译 Person.cs
文件到 .dll
文件(使用 csc /target:library Person.cs
),然后在我尝试编译时引用库文件 Registry.cs
( csc /r:"./Person.dll" /out:test.exe Registry.cs
)。这有效,但似乎根本不是正确的工作流程。如果你遇到过类似的,请帮忙。下面是两个类的源代码。
Person.cs
using System;
namespace ClassTest {
public class Person {
private string Name {set; get;}
private int Age {set; get;}
public Person(string name, int age) {
Name = name;
Age = age;
}
public void GetInfo() {
Console.WriteLine("Name: " + Name);
Console.WriteLine("Age: " + Age + "\n");
}
}
}
Registry.cs
using System;
namespace ClassTest {
public class Registry {
Person[] citizens;
public Registry() {
citizens = new Person[2];
citizens[0] = new Person("John", 30);
citizens[1] = new Person("Mary", 22);
foreach (Person p in citizens) {
p.GetInfo();
}
}
public static void Main() {
Console.WriteLine("");
Registry r = new Registry();
}
}
}
最佳答案
我希望我能给你一个更好的答案,但问题似乎归结为你编译的不是一个项目,而是一堆松散的 .cs 文件。
在编译 Registry.cs 时,编译器不知道 Person.cs 中的内容,因此它无法确定您正在谈论的“Person”类型以及它具有的功能(包括所有重载)、属性和字段。这意味着它不能进行类型检查。更不用说将该类的真实 IL 名称放入代码中,以避免任何混淆。它只会停止。
A clunky workaround I found after some time was to compile the Person.cs file to a .dll file (with csc /target:library Person.cs
这就是它与您引用的所有 .NET 库(包括 System.dll)一起工作的方式。所有这些都已预编译,这就是为什么您可以在没有源代码的情况下使用它们。您现在可以在线查找他们的源代码,但这不是给定的。尤其是对于 3rd 方 .dll,这是很少有的。
我只能告诉你,当我学习 Native C++ 时,我们是如何做到的。我们不使用使用,而是使用包含。 Wich 实际上更像是添加一个引用。我们必须在使用该类的每个文件中都包含 Person.h。这包括 Registry.h。但是 IIRC,也是使用 Registry.h 的每个文件。这当然会导致使用 Registry.h 的文件重复,因为它有两个 Person-h - 一个本身,一个来自 Registery.h 的包含。编译器通过预处理器的方式可以解决这个问题,但速度很慢。因此,我们的每个代码文件都以这些预处理器指令开始和结束:
#ifndef CustomIdenfifer
#define CustomIdentifer
//Code
#endif
您可以在整个库源文件中看到它:https://code.woboq.org/llvm/libcxx/include/string.html
这以某种方式阻止了相同的包含源代码最终出现两次,同时仍然允许单独编译每个文件。现在 Visual Studio 和 Projecet 文件以某种方式摆脱了手动执行此操作的需要。你没有和他们一起工作,所以你必须手动完成。
至于怎么样?我不知道为什么。正如我所说,我只知道在我过去的 Native C++ 时代。近二十年来,我没有与没有 GUI 的编译器交谈过。
关于c# - 尝试使用自定义类编译类会导致错误 CS0246,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59435148/