【问题标题】:C#: Can't include class from annother namespace [duplicate]C#:不能包含来自另一个命名空间的类[重复]
【发布时间】:2021-03-10 11:44:32
【问题描述】:

我有一个奇怪的问题。

我创建了两个类 AdvertisementHelper(namespace AdvertisementHelper) 和 Doof (namespace blabla),现在我想使用 AdvertisementHelper 类中 Doof 类的方法 bad_code。

AdvertisementHelper.cs:

using blabla;
namespace AdvertisementHelper
{
    class AdvertisementHelper
    {
        Doof d = new Doof();
        d.bad_code();
    }
}

Doof.cs:

namespace blabla
{
    class Doof
    {
        public void bad_code()
        {
        }
    }
}

这不是我的第一个 C# 程序,我已经做过很多次了,我从来没有遇到过这样的问题。 blabla 和 AdvertisementHelper 是同一个 Visual Studio 项目的一部分。

d.bad_code 和 bad_code 未在此上下文中定义

.NET 框架 4.7.2

【问题讨论】:

  • 公开类Doof
  • 两个类都定义在同一个程序集中,因此它仍应使用默认值internal
  • 代码不在方法中...
  • @Fildor 好收获

标签: c# .net visual-studio


【解决方案1】:

你不能让代码(也就是方法调用)在类的任何地方浮动。

class AdvertisementHelper
{
    Doof d = new Doof(); // <= OK, because interpreted as class field
    d.bad_code();        // <= doesn't work!
}

例如,您需要将其放入方法中。

class AdvertisementHelper
{
    Doof d = new Doof(); // <= OK, because interpreted as class field

    public void Execute()
    {
        d.bad_code();    // <= Inside a method = OK!
    }
}

【讨论】:

  • 天哪,我太笨了哈哈哈:D
  • @Simon2215 告诉你他没有犯那个确切错误的人从 5 分钟前就在对你撒谎或编码。 ;)(我们都做到了——至少一次。)
  • 我已经编程多年并没有注意到这个 wtf :D 谢谢 xdd
  • 这就是其中之一......你看到它或你没有看到它。如果你不这样做,你可以看它 1000 次然后想知道。然后你不喜欢的同事走过你的屏幕,然后......
猜你喜欢
  • 2011-03-21
  • 2014-08-26
  • 2018-02-04
  • 2019-03-14
  • 2017-07-21
  • 1970-01-01
  • 2011-12-09
  • 2012-05-27
  • 1970-01-01
相关资源
最近更新 更多