【发布时间】:2015-07-08 06:36:03
【问题描述】:
在 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# 中找不到类似的东西。
【问题讨论】:
-
你在寻找类似
Activator.CreateInstance(yourTypeGoesHere)的东西吗? -
C# 没有元类。所以没有直接模拟。是的,你可以使用反射,但我真的不喜欢那样。我个人认为最好的方法是我在链接的欺骗中的回答中写道:还有一个选择是用返回对象的新实例的委托字典替换你的类字典。使用 lambda 语法,该选项会产生非常干净的代码。