传入枚举作为方法参数

时间:2013-09-23 09:06:12

标签: c# enums

我宣布了一个枚举:

public enum SupportedPermissions
{
    basic,
    repository,
    both
}

我也有像这样的POCO:

public class File
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public SupportedPermissions SupportedPermissions { get; set; }      
}

现在我想创建一个方法,我可以用它来创建一个新的File对象:

public string CreateFile(string id, string name, string description, Enum supportedPermissions)
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions.basic
    };

    return file.Id;
}

我如何为枚举创建参数以及如何在我的伪代码SupportedPermissions = supportedPermissions.basic中分配它,以便我的File实例设置了SupportedPermissions?

4 个答案:

答案 0 :(得分:35)

更改CreateFile方法的签名以期望SupportedPermissions值而不是普通枚举。

public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions
    };

    return file.Id;
}

然后,当您调用方法时,将SupportedPermissions值传递给方法

  var basicFile = CreateFile(myId, myName, myDescription, SupportedPermissions.basic);

答案 1 :(得分:5)

如果要传入要使用的值,则必须使用声明的枚举类型并直接使用提供的值:

public string CreateFile(string id, string name, string description,
              /* --> */  SupportedPermissions supportedPermissions)
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions // <---
    };

    return file.Id;
}

如果您想要使用固定值,则根本不需要任何参数。相反,直接使用枚举值。语法类似于类的静态成员:

public string CreateFile(string id, string name, string description) // <---
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = SupportedPermissions.basic // <---
    };

    return file.Id;
}

答案 2 :(得分:4)

首先将方法参数Enum supportedPermissions更改为SupportedPermissions supportedPermissions

然后像这样创建你的文件

file = new File
{  
    Name = name,
    Id = id,
    Description = description,
    SupportedPermissions = supportedPermissions
};

对你的方法的调用应该是

CreateFile(id, name, description, SupportedPermissions.basic);

答案 3 :(得分:0)

public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
{
    file = new File
    {  
       Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions
    };

    return file.Id;
}