You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在C#中使用自定义命名空间?编译报错求助

解决Mono环境下自定义命名空间引用错误的问题

你遇到的问题主要来自两个核心点:命名空间拼写不匹配,以及编译时未包含自定义类文件,下面一步步帮你搞定:

1. 修正命名空间拼写不一致的问题

你的主程序里写的是using myComponents;(注意末尾的s),但自定义类的命名空间是namespace myComponent(没有s),这直接导致编译器找不到对应的命名空间。

你需要把两者统一:

  • 要么把主程序中的using myComponents;改成using myComponent;
  • 要么把自定义类的命名空间改成namespace myComponents;

2. 编译时必须包含所有相关的.cs文件

你当前的编译命令只指定了helloworld.cs,编译器根本不知道还有另一个自定义类的文件存在,自然无法识别myComponent命名空间下的类型。

假设你的自定义类文件名叫myStringClass.cs,请修改编译命令为:

csc helloworld.cs myStringClass.cs -r:System.Windows.Forms.dll

这样编译器会同时编译两个文件,就能正常识别到自定义命名空间里的myString类了。

可选方案:先编译自定义类为独立DLL再引用

如果你希望把自定义组件封装成可复用的库,也可以分两步编译:

  1. 先把自定义类编译成动态链接库:
csc /target:library myStringClass.cs

这会生成myStringClass.dll文件。
2. 再编译主程序时引用这个DLL:

csc helloworld.cs -r:System.Windows.Forms.dll -r:myStringClass.dll

修正后的完整代码示例

自定义类文件(myStringClass.cs)

namespace myComponent
{
    public static class myString
    {
        public static string FirstString
        {
            get
            {
                return "connection";
            }
        }
    }
}

主程序文件(helloworld.cs)

using System;
using System.Windows.Forms;
using myComponent; // 修正后的命名空间引用

public class HelloWorld : Form
{
    static public void Main ()
    {
        Application.Run (new HelloWorld ());
    }

    public HelloWorld ()
    {
        Text = "Hello Mono World " + myString.FirstString;
    }
}

执行正确的编译命令后,程序就能正常运行了。

内容的提问来源于stack exchange,提问作者Raymond.Cao

火山引擎 最新活动