【问题标题】:How to access static class in different file from partial class如何从部分类访问不同文件中的静态类
【发布时间】:2012-11-28 10:09:39
【问题描述】:

我在 Form1.cs 中有部分类 Form1 。 我在 Sample.cs 文件中有 ManagedIpHelper 静态类。

我想从 Form1 类中的方法访问该静态类中的方法。但是当我使用它时,它显示在当前上下文中不存在。 在这两个文件名命名空间是相同的。我在 Sample.cs 文件中有另一个名为 TcpRow 的类。这是正常的public class,并且可以从 Form1 的方法中访问,没有错误。

对此有什么建议的解决方案?

编辑

对不起。

TcpRow a; foreach (TcpRow tcpRow in ManagedIpHelper.GetExtendedTcpTable(true))

对于这段代码,第一行有错误TcpRow could not be found(are you missing a using directive... 第二行只有错误:ManagedIpHelper 在当前上下文中不存在。

编辑 2

示例.cs

Form1.cs

【问题讨论】:

  • 你能给我们看一点代码吗? (例如类及其方法;方法的内容已被缩短/删除)
  • 能否贴出 TcpRow、ManagedIpHelper 和 Form1 的命名空间声明?
  • @soham.m17 快速健全性检查:您已经以当前形式保存并重新编译了它,对吧?
  • 是的。很抱歉出现缩进和其他查看问题。
  • @soham.m17 还有其他错误,还是只有这两个?

标签: c# .net class static


【解决方案1】:

静态类中的方法是private还是protected?这会导致该方法不可见。

【讨论】:

  • 方法在静态类中是公共的。
【解决方案2】:

静态类的命名空间可能与 Form1.Cs 的命名空间不同,如果它们不同,则应确保在 Form1.cs 类的顶部添加 using 语句。

 using NetProject;

另外,要调用静态方法,你应该这样调用它。

 ManagedHelper.MethodName(....)

您的 sample.cs 文件应如下所示。此代码将编译,但建议您将类分成不同的文件。

Form1.cs

namespace NetProject
{
    using System;
    using System.Collections.Generic;

    public partial class Form1
    {
        public void SomeMethod()
        {
            TcpRow row;

            foreach (TcpRow tcpRow in ManagedIpHelper.GetExtendedTcpTable(true))
            {

            }
        }
    }
}

Sample.cs

namespace NetProject
{
    using System;
    using System.Collections.Generic;

    public class TcpTable : IEnumerable<TcpRow>
    {
        public IEnumerator<TcpRow> GetEnumerator()
        {
            throw new NotImplementedException();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            // You should implement this method
            throw new NotImplementedException();
        }
    }

    public class TcpRow
    {

    }

    public static class ManagedIpHelper
    {
        public static TcpTable GetExtendedTcpTable(bool value)
        {
            // You should implement this method
            return new TcpTable();
        }
    }
}

查看MSDN 上有关命名空间的文档。

【讨论】:

  • 我已将命名空间更改为相同。他们都有相同的命名空间。此外,我通过 ManagedIpHelper.Methodname() 调用该方法仍然显示错误。
  • 还需要添加 TcpRow 的命名空间。
  • TcpRow 和 ManagedIpHelper 在同一个文件 sample.cs 中。并且该文件具有与 form1.cs 相同的命名空间。
  • @soham.m17 要么是类inside 另一个类,还是直接在命名空间声明中?
  • 为什么要在 sample.cs 中再次导入 Form1?它已经在 Form1.cs 中。 sample.cs 和 Form1.cs 只有一个命名空间 NetProject。那么,你能解释一下吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-25
  • 2013-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多