ASP.NET中方法和类型之间的一般区别是什么?

时间:2014-02-05 20:14:14

标签: c# asp.net

我正在创建一个在线应用程序,它需要一些C#代码。所以我创建了一个新的文件名:User.cs,在该文件中我有这个代码:

public class UserProperties {
    public string hasPermission (string permission) {
        // get the permissions of the user
        var db = Database.Open("VMS");
        var roles = db.Query("SELECT * FROM webpages_UsersInRoles 
        WHERE UserId =@0", WebSecurity.CurrentUserId);
        // Get the Role Id
        var getRole = "";
        foreach (var row in roles) {
            getRole = row.RoleId.ToString();
        }
        // Get the permission ID
        var permissions = db.Query("SELECT * FROM Permissions WHERE 
        LOWER(Permission_Name) = LOWER(@0)", permission);
        var permissionId = "";
        foreach (var row in permissions) {
            permissionId = row.Permission_Id.ToString();
        }
        // Now get the rolePermissions
        var role_permissions = db.Query("SELECT * FROM Role_Permissions 
        WHERE Role_Id =@0 AND Permission_Id =@1", getRole, permissionId);
        if(role_permissions.Count() == 0) {
            return "Not Allowed.";
        } else {
            return "Yes, full permission.";
        }
    }
}

此代码将查找用户的权限,然后返回一个值。但它没有发生。当我尝试执行它时:

@{ 
  new UserProperties.hasPermission("Create_Page");
}

它给了我一个例外:

  

CS0118:'User.hasPermission(string)'是'方法',但用作'类型'

我不确定我是如何使用它作为一种类型的?

4 个答案:

答案 0 :(得分:4)

您需要使用:

new UserProperties().hasPermission("Create_Page")

或者,您可以使hasPermission为静态,然后您不需要创建实例

public static string hasPermission (string permission) { ... }

@{ 
  UserProperties.hasPermission("Create_Page");
}

答案 1 :(得分:2)

您的代码的第一行:

public class UserProperties

定义(对象)类型。

您声明实例方法的下一行。

public string hasPermission (string permission)

除非您创建UserProperties的实例..

var userProperties = new UserProperties();

您无法拨打hasPermission()

您也可以(不推荐)创建静态方法。

public static string hasPermission (string permission)

MSDN Docs 10.5.2 - Static and instance methods

答案 2 :(得分:0)

您需要做的只是添加括号:

@{ 
  new UserProperties().hasPermission("Create_Page");
}

new UserProperties()创建UserProperties类的实例,然后在其上调用hasPermission方法。

如果hasPermission被定义为static,那么您的语法将是有效的(您不需要实例来调用该方法)。

答案 3 :(得分:0)

你必须创建一个UserProperties实例。

var up = new UserProperties();
up.hasPermission("Create_Page");

或只是

new UserProperties().hasPermission("Create_Page");
相关问题