2012-01-16 206 views
-2

在一个名为Security类,有一个方法:C#静态公共方法

public static bool HasAccess(string UserId, string ModuleID) 

如何调用该方法,所以它可以返回一个布尔结果呢?

我试过followoing却并不顺利:

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

回答

2

你只需要使用类名。无需创建实例。

Security.HasAccess(...) 
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 
0

由于这是一个静态方法,你应该做类似下面。

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

,如果它是一个静态方法,然后调用它会像这样的方式:

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

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