【问题标题】:Is there a way to initialize an object from a reference class in C#? [duplicate]有没有办法从 C# 中的引用类初始化对象? [复制]
【发布时间】: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 语法,该选项会产生非常干净的代码。

标签: c# class delphi reference


【解决方案1】:

像这样使用Type

public class TShape { }

还有:

Type t = typeof(TShape);

要通过t变量初始化对象,请使用Activator.CreateInstance(t)

Shape shp = (Shape)Activator.CreateInstance(t);

【讨论】:

  • 这只是我问题的一半,我应该如何通过“t”变量初始化一个对象 Type t = typeof(TCircle);形状 shp = new t(); ?
  • 像这样:Shape shp = (Shape)Activator.CreateInstance(t);请参阅我的更新答案。
  • 非常感谢,你真的很有帮助:)
  • 如何给构造函数传参?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多