Pass in an enum as a method parameter

前端 未结 4 1665
北海茫月
北海茫月 2020-12-30 18:52

I have declared an enum:

public enum SupportedPermissions
{
    basic,
    repository,
    both
}

I also have a POCO like this:

<         


        
相关标签:
4条回答
  • 2020-12-30 19:30

    Change the signature of the CreateFile method to expect a SupportedPermissions value instead of plain Enum.

    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;
    }
    

    Then when you call your method you pass the SupportedPermissions value to your method

      var basicFile = CreateFile(myId, myName, myDescription, SupportedPermissions.basic);
    
    0 讨论(0)
  • 2020-12-30 19:35

    First change the method parameter Enum supportedPermissions to SupportedPermissions supportedPermissions.

    Then create your file like this

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

    And the call to your method should be

    CreateFile(id, name, description, SupportedPermissions.basic);
    
    0 讨论(0)
  • 2020-12-30 19:37

    If you want to pass in the value to use, you have to use the enum type you declared and directly use the supplied value:

    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;
    }
    

    If you instead want to use a fixed value, you don't need any parameter at all. Instead, directly use the enum value. The syntax is similar to a static member of a class:

    public string CreateFile(string id, string name, string description) // <---
    {
        file = new File
        {  
            Name = name,
            Id = id,
            Description = description,
            SupportedPermissions = SupportedPermissions.basic // <---
        };
    
        return file.Id;
    }
    
    0 讨论(0)
  • 2020-12-30 19:39
    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;
    }
    
    0 讨论(0)
提交回复
热议问题