CS0118:“变量”是一个变量,但像类型一样使用

发布于 2025-01-16 08:42:44 字数 497 浏览 1 评论 0原文

我有 2 个 cs 文件,一个名为 Heading,一个名为 Accounts。标题文件中有一个名为 Heading 的类,我想在 Accounts cs 文件中使用其中的一些方法。我去创建一个实例:

Heading heading = new Heading();

然后,当我使用标题时,我无法访问标题方法,并且标题中出现错误。但是我可以使用

Heading.GetThis();

我试图找出为什么有时我必须创建另一个cs文件的实例,有时我必须直接调用cs文件类,因为我在同一个项目中有另一个名为AccountName的cs文件,我在那里创建实例

AccountName accountName = new AccountName();

然后我使用了所有 AccountNames 方法。

抱歉,如果这没有成功,因为我尝试用谷歌搜索此错误,但没有看到我正在查看的解决方案。

I have 2 cs files one named Heading and one named Accounts. There is a class in the Heading file named Heading and I want to use some of the methods in there in the Accounts cs file. I went to create an instance:

Heading heading = new Heading();

Then when I use the heading I don't have access to the Heading methods and I get the Error in the title. However I can use

Heading.GetThis();

I'm trying to find out why sometime I have to create an instance of another cs file and sometime I have to call the cs file class directly as I have in the same project another cs file called AccountName and there I had to create the instance

AccountName accountName = new AccountName();

Then I had uses of all the AccountNames methods.

Sorry if this didn't make since I tried to google this error but didn't see a solution for what i'm looking at.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

郁金香雨 2025-01-23 08:42:44

要扩展评论中给出的答案:

public class Heading
    {
        private Heading()
        {

        }
        public static Heading GetThis()
        {
            return new Heading();
        }
    }

上面的代码创建了您解释的条件。 Heading.cs 隐藏其构造函数以强制用户以特定方式实例化它。您的 Heading.cs 很可能使用单例设计模式。如果是这样的话,应该有充分的理由。
此 YouTube 视频讨论了什么是单例

替代方案: 按照预期使用 Heading.cs其设计者Heading header = Heading.GetThis();。或者修改 Heading.cs 为

//make constructor public 
        public Heading()
        {
        }

To expand on the answer given in comments:

public class Heading
    {
        private Heading()
        {

        }
        public static Heading GetThis()
        {
            return new Heading();
        }
    }

Code above creates the condition you explained. The Heading.cs is hiding its constructor to force its users to instantiate it in a specific way. There is a good chance that your Heading.cs is using singleton design pattern. If that is the case there should be a good reason for it.
This youtube video discusses what is singleton

Alternatives : use Heading.cs as intended by the its designer Heading heading = Heading.GetThis();. Or modify Heading.cs to

//make constructor public 
        public Heading()
        {
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文