如何使用Type作为get class object的“as”关键字
以下是一个例子:
class A
{
public string Test { get; set; }
public Type Type { get; set; }
}
class B
{
public string F { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
var a = new A();
a.Type = typeof(B);
var getB = (a.Type)Activator.CreateInstance(a.Type);
getB.F = "Say something ...";
}
}
此代码不起作用我试图从Typeof
获取类对象答案 0 :(得分:3)
您无法声明在编译时未知的类型对象,就像您在此处尝试的那样:
var getB = (a.Type)Activator.CreateInstance(a.Type);
这应该有效:
public static void Main(string[] args)
{
var a = new A();
A.Type = typeof(B);
var getB = (B)Activator.CreateInstance(a.Type);
getB.F = "Say something ...";
}
或者使用as运算符:
var getB = Activator.CreateInstance(a.Type) as B;
如果您在编译时不知道实际类型,则另一种方法是使用dynamic关键字:
dynamic getB = Activator.CreateInstance(a.Type);
//it will compile but will throw runtime erros if getB does not have F property setter
getB.F = "Say something ...";