访问class-c#中的静态函数

时间:2015-11-13 06:33:23

标签: c# oop static

我从HackerRank

获取了以下代码段
class myfun
{
    int x;
    static int y;
    void fun()
    {
        x = 1;
        y = 1;
    }
    static void gun()
    {
        x = 1;//An object reference error
        y = 1;
    }
    static void Main()
    {
       myfun.gun();
       //Error  1   The namespace already contains a definition for 'myfun' 
    }
}

为什么这个错误表明它已包含定义?

编辑:我在同一个解决方案中交叉检查了其他文件,发现它已被用于另一个类文件中。所以其中一个问题就解决了。错误已包含定义已解决。但仍不清楚如何在静态函数中使用变量。我可以通过将其更改为静态来实现它。但任何人都可以为此建议替代方案吗?

在静态方法中访问变量的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

您的代码无法编译

x

可能你应该让main 静态;另一个问题是,如果你的意思是标准的C方法(就像C++Java // Note capitalization static void Main() { ... } 中那样),你应该这样说:

select a.Date, b.id_room, (b.num-count(c.datex)) as remain
from (
select curdate() - INTERVAL (a.a + (10 * b.a) - (100 * c.a)) DAY as Date
from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
) a cross join rooms b  join visit c on c.datex where a.Date between '2015-11-11' and '2015-11-12' group by b.id_room,a.Date

https://msdn.microsoft.com/en-us/library/ms228506(v=vs.90).aspx

答案 1 :(得分:0)

你的第一个问题是你是从静态方法调用X.那应该在那里抛出一个错误。这是一个错误的函数,你试图从其他函数调用,调用是正确的,但你调用的函数是错误的,所以它永远不应该工作。你最好使X也是静态的。

相关问题