有没有办法从 C# 中的引用 class 初始化对象?
Is there a way to initialize an object from a reference class in C#?
在 Delphi 中,当我想从不确定派生的 class
创建一个 object
时,我使用的是 class of
语句;
TShape = class
public
procedure Draw;
end;
TCircle = class(TShape)
public
procedure Draw;
end;
TShapeClassRef = class of TShape;
我正在创建对象;
var
ref:TShapeClassRef;
drawing:TShape;
begin
ref:=TCircle;
drawing:=ref.Create;
drawing.draw; //this is a circle object, and it draws circle
end;
我在 c# 中找不到类似的东西。
像这样使用Type
:
public class TShape { }
并且:
Type t = typeof(TShape);
要通过 t
变量初始化对象,请使用 Activator.CreateInstance(t)
:
Shape shp = (Shape)Activator.CreateInstance(t);
在 Delphi 中,当我想从不确定派生的 class
创建一个 object
时,我使用的是 class of
语句;
TShape = class
public
procedure Draw;
end;
TCircle = class(TShape)
public
procedure Draw;
end;
TShapeClassRef = class of TShape;
我正在创建对象;
var
ref:TShapeClassRef;
drawing:TShape;
begin
ref:=TCircle;
drawing:=ref.Create;
drawing.draw; //this is a circle object, and it draws circle
end;
我在 c# 中找不到类似的东西。
像这样使用Type
:
public class TShape { }
并且:
Type t = typeof(TShape);
要通过 t
变量初始化对象,请使用 Activator.CreateInstance(t)
:
Shape shp = (Shape)Activator.CreateInstance(t);