2012-01-16 204 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的定義類。