大家我需要一些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;
大家我需要一些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;
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
你的'Button1Click'有一個錯誤:你不要調用'Int'的構造函數。此外,請省略「運行代碼片段/複製代碼片段以應答」按鈕 - 它們對Delphi代碼沒有任何用處。 – MartynA
您可以使用:
StrToInt(s)
和
IntToStr(i)
功能。
謝謝,但我不需要那樣...! 看這個例子。 '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
最簡單的方法是使用這兩種方法:
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
如果您使用的是德爾福最新版本,除了以前的答案,您也可以使用僞OOP語法您想當初 - 命名約定只是ToXXX不AsXXX:
Int := Str.ToInteger
Str := Int.ToString;
該整數助手還增加了解析和方法的TryParse:
Int := Integer.Parse(Str);
if Integer.TryParse(Str, Int) then //...
你爲什麼在這裏說「僞」?它對我來說看起來很簡單的OOP語法。 –
我的意思是字符串和整數仍然不是任何合適的OOP意義上的對象(沒有繼承等) –
我不會說OOP需要繼承。考慮一個值類型是一個密封類。 –
不安全鑄造用'StrToInt'功能,安全鑄造如'TryStrToInt'。 – TLama
要添加到TLama - 也有'StrToIntDef' – ain
和相反的轉換:http://stackoverflow.com/questions/14317264 - 爲SO互連 –