gpt4 book ai didi

delphi - Chris Rolliston XE2 Foundations中需要澄清按位运算符第65页

转载 作者:行者123 更新时间:2023-12-03 18:57:16 25 4
gpt4 key购买 nike

我是克里斯的书中的新手,这是一个问题。

在第65页的最后一段中提到使用适当的集合类型,因为它们提供强类型。

有人可以解释一下这是什么意思,因为下面的示例看起来像我通常要做的事情,因此我试图使用更好的做法。

最佳答案

由于我无法侵犯自己的版权,因此请完整填写以下部分:

Delphi RTL中有几个地方-Windows API中有很多地方-其中使用某种整数的“位掩码”代替适当的设置类型。例如,System.SysUtils单元声明一个函数FileGetAttr,该函数以单个整数的形式返回文件的属性(只读,隐藏,系统等)。要测试各个属性,必须使用所谓的“按位”运算符,尤其是and

uses
System.SysUtils;

var
Attr: Integer;
begin
Attr := FileGetAttr('C:\Stuff\Some file.txt');
if Attr and faReadOnly <> 0 then
WriteLn('Read only');
if Attr and faHidden <> 0 then
WriteLn('Hidden');
if Attr and faSysFile <> 0 then
WriteLn('System');
end.


为此,必须定义 faXXX常量,以便第一个常量的值为1,第二个常量的值为2,第三个常量的值为4,第四个值为8,依此类推。要将值添加到现有手册“集合”中,请使用 or,要删除值,请使用 and not

procedure AddHiddenAttr(const AFileName: string);
begin
FileSetAttr(AFileName, FileGetAttr(AFileName) or faHidden);
end;

procedure RemoveHiddenAttr(const AFileName: string);
begin
FileSetAttr(AFileName, FileGetAttr(AFileName) and not faHidden);
end;


通常,应该在适当的地方使用适当的集合类型,因为它们提供了强大的键入功能和更高的可读性。但是,以下代码展示了一个事实,即在引擎盖下,“真实”集合及其手动C样式等效项归结为同一件事:

const
mcFirst = 1;
mcSecond = 2;
mcThird = 4;
mcFourth = 8;

type
TMyEnum = (meFirst, meSecond, meThird, meFourth);
TMySet = set of TMyEnum;

var
UsingSet: TMySet;
UsingConsts: LongWord;
begin
//direct assignment
UsingSet := [meSecond, meThird];
UsingConsts := mcSecond or mcThird;
WriteLn('Equal? ', Byte(UsingSet) = UsingConsts);
//subtraction
Exclude(UsingSet, meSecond);
UsingConsts := UsingConsts and not mcSecond;
WriteLn('Equal? ', Byte(UsingSet) = UsingConsts);
//addition
Include(UsingSet, meFourth);
UsingConsts := UsingConsts or mcFourth;
WriteLn('Equal? ', Byte(UsingSet) = UsingConsts);
//membership test
if meThird in UsingSet then WriteLn('meThird is in');
if UsingConsts and mcThird <> 0 then WriteLn('mcThird is in');
end.


运行该程序,您会发现在每种情况下输出的 TRUE

所以...刚刚经历了枚举和设置类型,现在我将介绍弱类型的等效项。最后,该位的含义是,如果您习惯于以C方式定义简单的位掩码,则没有理由避免在Delphi中使用正确的集合类型,因为它们归结为同一件事。因此,您不会因为获得强类型而失去任何效率-在这种情况下,“强类型”本身就意味着您不会偶然分配或测试旨在用于另一类集合的元素。

关于delphi - Chris Rolliston XE2 Foundations中需要澄清按位运算符第65页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19573277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com