代码之家  ›  专栏  ›  技术社区  ›  Anirudh Goel

根据c中的条件将枚举值分配给枚举#

  •  0
  • Anirudh Goel  · 技术社区  · 17 年前

    public enum file_type {readonly, readwrite, system}
    

    if("file is markedreadonly")
       file_type = readonly;
    

    在c语言中可以这样做吗#

    4 回复  |  直到 17 年前
        1
  •  7
  •   SolutionYogi Eric Lippert    17 年前

    通过写入文件_type=readonly,您试图在运行时更改枚举的定义,这是不允许的。

    创建file_type类型的变量,然后将其设置为只读。

    此外,请使用.NET命名标准来命名变量和类型。此外,对于枚举,建议将“无”枚举作为第一个值。

    public enum FileType { None, ReadOnly, ReadWrite, System}
    
    FileType myFileType = FileType.None;
    
    if( //check if file is readonly)
        myFileType = FileType.ReadOnly;
    
        2
  •  1
  •   John Saunders    17 年前

    你的语法错了。文件类型是一种类型,而不是变量。另外,您需要@readonly,因为readonly是一个保留字。

        3
  •  0
  •   nickd    17 年前

    枚举本身的行为更像类型。您需要一个类型为的变量 文件类型 然后您可以将其分配给 文件\u type.readonly

    public enum FileType
    {
        ReadOnly,
        ReadWrite,
        System
    }
    
    FileType ft;
    
    if (...) ft = FileType.ReadOnly;
    
        4
  •  0
  •   Malcolm    17 年前

    你完全可以这样做,几乎完全如你所说。注:我已更改了外壳,以符合公认的C#编码准则。

    
    public enum FileType { ReadOnly, ReadWrite, System }
    
    

    ...

    FileType fileType; FileInfo file = new FileInfo("C:\full\path\to\file"); if (file.IsReadOnly) fileType = FileType.ReadOnly

    另外,请查看System.IO.FileAccess和System.IO.FileAttribute枚举。它们可能会为您提供更合适的标准实现。就个人而言,我更喜欢使用系统类型,而不是“自己滚动”——工作量更少,更容易被其他程序员理解。

    嗯