2014-01-20 55 views
0

大家我需要一些ESAY办法从整型和字符串在Delphi改变7更改为整数

var 
Str:String; 
Int:Integer; 
// Here what i need to do 
Str:='123'; 
Int:=Str.AsInteger 
// or use this 
Int:=123; 
Str=Int.AsString; 
+1

不安全铸造用'StrToInt'功能,安全铸造如'TryStrToInt'。 – TLama

+1

要添加到TLama - 也有'StrToIntDef' – ain

+1

和相反的转换:http://stackoverflow.com/questions/14317264 - 为SO互连 –

回答

-1
type 
TForm1 = class(TForm) 
Button1: TButton; 
Edit1: TEdit; 
procedure Button1Click(Sender: TObject); 
end; 

Integer = class 
FValue: System.Integer; 
function ToString: string; 
public 
property Value: System.Integer read FValue write FValue; 
end; 

var 
Form1: TForm1; 

implementation 

function Integer.ToString: string; 
begin 
Str(FValue, Result); 
end; 

procedure TForm1.Button1Click(Sender: TObject); 
var 
Int:integer; 
begin 
Int.Value:=45; 
Edit1.Text:=Int.ToString; 
end; 
end 
+0

你的'Button1Click'有一个错误:你不要调用'Int'的构造函数。此外,请省略“运行代码片段/复制代码片段以应答”按钮 - 它们对Delphi代码没有任何用处。 – MartynA

1

您可以使用:

StrToInt(s) 

IntToStr(i) 

功能。

+0

谢谢,但我不需要那样...! 看这个例子。 'type TForm1 = class(TForm) Button1:TButton; Edit1:TEdit; 程序Button1Click(Sender:TObject); 结束; Integer = class FValue:System.Integer; 函数ToString:string; public 属性值:System.Integer读取FValue写入FValue; 结束; var Form1:TForm1; implementation function Integer.ToString:string; 开始 Str(FValue,Result); 结束; procedure TForm1.Button1Click(Sender:TObject); var op:integer; begin op.Value:= 45; Edit1.Text:= op.ToString; 结束; end.' – Ali

6

最简单的方法是使用这两种方法:

IntVal := StrToInt(StrVal); // will throw EConvertError if not an integer 
StrVal := IntToStr(IntVal); // will always work 

您还可以使用更多的容错TryStrToInt(远比捕捉EConvertError越好):

if not TryStrToInt(StrVal, IntVal) then 
    begin 
    // error handling 
    end; 

如果你想诉诸默认值,而不是显式处理错误,您可以使用:

IntVal := StrToIntDef(StrVal, 42); // will return 42 if StrVal cannot be converted 
3

如果您使用的是德尔福最新版本,除了以前的答案,您也可以使用伪OOP语法您想当初 - 命名约定只是ToXXX不AsXXX:

Int := Str.ToInteger 
Str := Int.ToString; 

该整数助手还增加了解析和方法的TryParse:

Int := Integer.Parse(Str); 
if Integer.TryParse(Str, Int) then //... 
+0

你为什么在这里说“伪”?它对我来说看起来很简单的OOP语法。 –

+0

我的意思是字符串和整数仍然不是任何合适的OOP意义上的对象(没有继承等) –

+0

我不会说OOP需要继承。考虑一个值类型是一个密封类。 –