位域与枚举

     今天在看C#的文件管理,看到了File.SetAttributes(this.textBox1.Text,MyAttributes|FileAttributes.System);从格式上说File.SetAttributes(string path,FileAttributes fileAttributes),为什么多一个“|”运算符呢?

      MSDN上给了一个例子:

ContractedBlock.gif ExpandedBlockStart.gif Code
using System;
using System.IO;
using System.Text;

class Test 
{
    
public static void Main() 
    {
        
string path = @"c:\temp\MyTest.txt";

        
// Create the file if it does not exist.
        if (!File.Exists(path)) 
        {
            File.Create(path);
        }

        
if ((File.GetAttributes(path) & FileAttributes.Hidden) == FileAttributes.Hidden) 
        {
            
// Show the file.
            File.SetAttributes(path, FileAttributes.Archive);
            Console.WriteLine(
"The {0} file is no longer hidden.", path);

        } 
        
else 
        {
            
// Hide the file.
            File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
            Console.WriteLine(
"The {0} file is now hidden.", path);
        }
    }
}


     仍然看不懂,只能从FileAttributes枚举变量下手,MSDN上对FileAttributes的定义:

     FileAttributes 枚举

     提供文件和目录的属性。

     此枚举有一个 FlagsAttribute 属性,通过该属性可使其成员值按位组合。

     那FlagsAttribute是怎么定义的呢

     FlagsAttribute 类

     指示可以将枚举作为位域(即一组标志)处理。

     看到这里大致可以弄清了问题的关键在于FileAttributes是个可以作为位域处理的枚举,那什么是位域?

     位域通常用于由可组合出现的元素组成的列表,而枚举常数通常用于由互相排斥的元素组成的列表。因此,位域设计为通过按位“或”运算组合来生成未命名的值,而枚举常数则不是。语言在对位域的使用和对枚举常数的使用上不同。

      位域通常用 2 的幂(即 1、2、4、8 等)定义枚举常量。这意味着组合的枚举常量中的各个标志都不重叠。

      测试数值中是否已设置标志的一种简便方法为:在数值和标志枚举常量之间执行按位“与”操作,这种方法会将数值中与标志不对应的所有位都设置为零,然后测试该操作的结果是否等于该标志枚举常量。

      所有概念解释清楚了,我们回过头来解释最开始我提出的问题:

      以FileAttributes为例,假设它有ReadOnly、HiddenSystem、Directory四个枚举常量(实际上不止这几个),因为用到位域,我们分别定义为1、2、4、8,化为二进制是0001、0010、0100、1000。

      如果文件Paths是ReadOnly且是System文件,它的FileAttributes就为0101(B),我们如果想为它加上Hidden属性,就可以使用:

      File.SetAttributes(Path, File.GetAttributes(path) | FileAttributes.Hidden);

      (0101) | (0010)=0111

      于是Path就具有了ReadOnly、HiddenSystem三个属性。

      如果我们用了File.SetAttributes(Path,  FileAttributes.Hidden);那实际上就是

      File.SetAttributes(Path, File.GetAttributes(path) & FileAttributes.Hidden);

      (0101) &(0010)=0000

      所有属性都消失了

      但是我们可以用

      IF((File.GetAttributes(path) & FileAttributes.Hidden) == FileAttributes.Hidden)

      来检测File是否具有Hidden属性。

转载于:https://www.cnblogs.com/Lazyloon/archive/2008/11/21/1338499.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值