其他方法在静态方法中看不到

时间:2014-09-09 00:35:31

标签: c# console-application static-methods

我正在尝试使用LINQ to Collection,但问题是ShowLINQ()无法在方法Main()中看到的方法。

class Program
{
    static void Main(string[] args)
    {
        ShowLINQ();//Error line
    }

    public void ShowLINQ()
    {
        List<Element> elements = BuildList();
        var query = from d in elements
                    where d.AtomicNumber < 22
                    orderby d.Name
                    select d;

        foreach (Element d in query)
        {
            Console.WriteLine(d.Name + " " + d.AtomicNumber);
        }
    }
    Snippet...
}

1 个答案:

答案 0 :(得分:5)

static基本上意味着您不需要new一个对象来查看它。它适用于该类的所有实例

如果没有static,您必须new一个对象才能看到它。

如果您想要从static方法与另一种方法进行通信,那么其他方法也必须是static

但请注意,反过来情况并非如此。您可以毫无问题地从实例方法与static方法进行通信。

所以你的解决方案是标记你的其他方法static ..以及它们共享的任何变量。