相关疑难解决方法(0)

我可以定义只包含这些值的MyType吗?

我有这个问题:例如,如果我有这些值:'AA','AB','AC','BC' - 我可以定义只包含这些值的MyType吗?

我想以这样的模式做:

type MyType = ... ; // something
var X: MyType;
begin
  x := 'AA' ;  // is valid, 'AA' is included in X 
  X := 'SS' ;  // not valid, 'SS' not is included in X, than raise an exception.
end; 
Run Code Online (Sandbox Code Playgroud)

我该如何解决?有没有直接使用类型数据的解决方案?

delphi delphi-xe2

4
推荐指数
1
解决办法
154
查看次数

是否可以声明具有不受0/1开始的受限长度的字符串类型?

在Delphi中,可以声明整数值的子范围.例如:

type
  myInt = 2..150
Run Code Online (Sandbox Code Playgroud)

这将myInt类型的值限制为2到150之间的值.但是,如果我想限制字符串的长度怎么办?

如果我写:

type 
  myString = string [150]
Run Code Online (Sandbox Code Playgroud)

我将mystring声明为150字节长,并将长度限制为从0,1,2等到150.但是,如何将长度限制在2到150之间,例如?当然,我可以检查字符串的长度并引发异常,但Delphi是否包含一些特定于这种情况的语法,类似于子范围的样式?

这显然不起作用,但我想要像:

type
  myString = string[2..150] 
Run Code Online (Sandbox Code Playgroud)

如果不可能,那么我可以检查长度,提出异常等.


试试这段代码:

var
 str1, str2, str3: TRestrictedString;
begin
  str1.Create(2, 5, 'pp');
  str2.Create(2, 5, 'aaaa');
  str3.Create(2, 10, str1 + str2);
  writeln (str3.getstring)
end
Run Code Online (Sandbox Code Playgroud)

要么:

var
 str1, str2, str3: TRestrictedString;
begin
  str1.Create(2, 5, 'pp');
  str2.Create(2, 5, 'aaaa');
  str3.Create(2, 10);
  str3.SetString(str1 + str2);
  writeln (str3.getstring)
end
Run Code Online (Sandbox Code Playgroud)

要么:

var
 str1, str2, str3: TRestrictedString;
begin
  str1.Create(2, 5, 'pp');
  str2.Create(2, 5, 'aaaa');
  str3.Create(2, 10);
  str3 := str1 + …
Run Code Online (Sandbox Code Playgroud)

delphi delphi-xe2

3
推荐指数
1
解决办法
720
查看次数

标签 统计

delphi ×2

delphi-xe2 ×2