为什么变量被声明为TStrings并创建为TStringList? [英] Why variables are declared as TStrings and created as TStringList?

查看:356
本文介绍了为什么变量被声明为TStrings并创建为TStringList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么变量被声明为 TStrings 并创建为 TStringList



例如:var sl 被声明为 TStrings ,但创建为 TStringList

  var 
sl:TStrings;
begin
sl:= TStringList.Create;

//添加字符串值...
sl.Add('Delphi');
sl.Add('2.01');

//使用索引获取字符串值
// sl.Strings(0)将返回
//'Delphi'
MessageDlg(
sl .Strings [0],
mtInformation,[mbOk],0);

sl.Free;
结束


解决方案

在我看来,这是没有意义的,尽管完全无害。你可以很好地声明 sl TStringList ,我一直这样做。对于代码读者来说,它使本地变量的列表更容易理解。



在这段代码中 sl 总是分配一个 TStringList 实例,所以没有什么可以从声明 sl 获得基类类型 TStrings 。但是,如果您将代码分配给变量的各种不同类型的 TStrings 后代,那么将其声明为 TStrings



通常情况下,您可能声明变量为 TStrings 的类型当代码没有显式创建实例时。例如,如果接收到一个 TStrings ,那么接收到字符串列表作为参数的实用程序方法将会更有用,因为可以将任何后代传递给它。这是一个简单的例子:

  procedure PrintToStdOut(Strings:TStrings); 
var
Item:string;
开始
在字符串中的项目
Writeln(Item);
结束

显然,当参数被声明为 TStrings 而不是 TStringList



但是,问题中的代码不是这个自然而言,如果 sl 宣称为 TStringList 类型,那么它将会如此轻微的改善。 p>

Why variables are declared as TStrings and created as TStringList?

eg: the var sl is declared as TStrings but created as TStringList

var
  sl : TStrings;
begin
  sl := TStringList.Create;

  // add string values...
  sl.Add( 'Delphi' );
  sl.Add( '2.01' );

  // get string value using its index
  // sl.Strings( 0 ) will return
  //   'Delphi'
  MessageDlg(
    sl.Strings[ 0 ],
    mtInformation, [mbOk], 0 );

  sl.Free;
end;

解决方案

To my mind that is rather pointless albeit completely harmless. You could perfectly well declare sl to be TStringList and I would always do it that way. For a reader of the code it makes the list of local variables easier to understand.

In this code sl is always assigned a TStringList instance and so there's nothing to be gained from declaring sl to have the base class type of TStrings. However, if you had code that assigned a variety of different types of TStrings descendants to the variable, then it would make sense to declare it as TStrings.

The situations when you might declare a variable to be of type TStrings would typically be when the code was not explicitly creating the instance. For example a utility method that received a string list as a parameter would be more useful if it accepted a TStrings since then any descendant could be passed to it. Here's a simple example:

procedure PrintToStdOut(Strings: TStrings);
var
  Item: string;
begin
  for Item in Strings do
    Writeln(Item);
end;

Clearly this is of much greater utility when the parameter is declared to be TStrings rather than TStringList.

However, the code in the question is not of this nature and I believe that it would be ever so mildly improved if sl was declared to be of type TStringList.

这篇关于为什么变量被声明为TStrings并创建为TStringList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆