c#静态公共方法

时间:2012-01-16 17:37:41

标签: c# public-method

在名为Security的类中,有一个方法:

    public static bool HasAccess(string UserId, string ModuleID)

如何调用此方法,以便返回bool结果?

我尝试了跟进,但没有成功:

    Security security = new Security();
    bool result = security.HasAccess("JKolk","Accounting");

4 个答案:

答案 0 :(得分:6)

bool result = Security.HasAccess("JKolk","Accounting");

要调用静态方法,您不需要实例化调用它的对象。

http://msdn.microsoft.com/en-us/library/79b3xss3.aspx

请注意,您可以混合使用静态和非静态成员,例如:

public class Foo
{
    public static bool Bar() { return true; }
    public bool Baz() { return true; }

    public static int X = 0;
    public int Y = 1;
}

Foo f = new Foo();
f.Y = 10; // changes the instance
f.Baz(); // must instantiate to call instance method

Foo.X = 10; // Important: other consumers of Foo within the same AppDomain will see this value
Foo.Bar(); // call static methods without instantiating the type

答案 1 :(得分:2)

您只需使用班级名称。无需创建实例。

Security.HasAccess( ... )

答案 2 :(得分:1)

如果它是一个静态方法,那么调用它的方式就是这样:

bool result = Security.HasAccess("JKolk","Accounting");

你不会使用Security类的实例,你会使用Security类的定义。

答案 3 :(得分:0)

由于这是一种静态方法,你应该做类似下面的事情。

 Security.HasAccess(("JKolk","Accounting");