转载于网络:
uses ComObj;
演示
Function calc(const expression : String):Integer;
Var
sc : OleVariant;
begin
//expresion := ‘100+5*3’;
sc := CreateOleObject('MSScriptControl.ScriptControl.1');
sc.Language :='JavaScript';
result := StrtoInt( sc.eval(expression) );
end;
Sample: 115 := calc(‘100+5*3’);
把字符串转换成delphi上可以执行的属性 (没看明白)
unit Unit2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TCustomFont = class
public
function Name : string;
function Size : integer;
end;
TCustomChartTitle = class
private
FFont : TCustomFont;
public
destructor Destroy; override;
function Font : TCustomFont;
end;
TCustomChart = class
private
FChartTitle : TCustomChartTitle;
public
destructor Destroy; override;
function ChartTitle : TCustomChartTitle;
end;
TForm2 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
FChart : TCustomChart;
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
uses System.Rtti, System.TypInfo;
{$R *.dfm}
procedure TForm2.Button1Click(Sender: TObject);
function Process(const Value : string; AObject : TObject) : TObject;
var
obj: TCustomChart;
rttiType: TRttiType;
rttiMethod: TRttiMethod;
rttiValue : TValue;
begin
result := nil;
rttiType := nil;
rttiMethod := nil;
rttiValue := nil;
rttiType := TRttiContext.Create.GetType(AObject.ClassType);
if rttiType = nil then
exit;
rttiMethod := rttiType.GetMethod(Value);
if rttiMethod = nil then
exit;
rttiValue := rttiMethod.Invoke(AObject, []);
if rttiValue.IsObject then
result := rttiValue.AsObject
else
if rttiValue.TypeInfo^.Kind = tkInteger then
ShowMessage(IntToStr( rttiValue.AsInteger))
else
ShowMessage(rttiValue.AsString);
end;
const
//注意: 如果要反射的字符串和方法名称不相同, 则需要转义
C_Font : array[0..1] of string = ('ChartTitle.Font.Name', 'ChartTitle.Font.Size');
var
i, j : integer;
sList : Tstringlist;
oObj : TObject;
begin
sList := Tstringlist.Create;
FChart := TCustomChart.Create;
try
sList.Delimiter := '.';
for i := Low(C_Font) to High(C_Font) do
begin
oObj := FChart;
sList.DelimitedText := C_Font[i];
for j := 0 to sList.Count - 1 do
begin
oObj := Process(sList.Strings[j], oObj);
if oObj = nil then
Break;
end;
end;
finally
FChart.Free;
sList.Free;
end;
end;
{ TCustomFont }
function TCustomFont.Size: integer;
begin
Result := 12;
end;
function TCustomFont.Name: string;
begin
Result := 'a';
end;
{ TCustomChartTitle }
destructor TCustomChartTitle.Destroy;
begin
if Assigned(FFont) then
FreeAndNil(FFont);
inherited;
end;
function TCustomChartTitle.Font: TCustomFont;
begin
if not Assigned(FFont) then
FFont := TCustomFont.Create;
Result := FFont;
end;
{ TCustomChart }
function TCustomChart.ChartTitle: TCustomChartTitle;
begin
if not Assigned(FChartTitle) then
FChartTitle := TCustomChartTitle.Create;
Result := FChartTitle;
end;
destructor TCustomChart.Destroy;
begin
if Assigned(FChartTitle) then
FreeAndNil(FChartTitle);
inherited;
end;
end.