我有一个类型对象。 我想从这种类型中获取对象实例。 (只是为了使用此对象的 ToString() 方法)。 参见:
public class P
{
public string s;
}
class Program
{
static void Main(string[] args)
{
P p = new P();
p.s = "foobar";
Type t = p.GetType();
P p2 = ((t.ToObjet()) as P).s;
Console.WriteLine(p2.s);
}
}
最佳答案
Activator.CreateInstance是你想要的。
Type givenType;
var obj = Activator.CreateInstance(givenType);
...
var obj = Activator.CreateInstance(givenType) as GivenType;
编辑:根据您的编辑,您想要的 Type
扩展方法 (ToObject
) 实际上是上面的代码。它必须创建一个新对象,因为您无法确定源对象是否仍然存在,即使使用该类型,您也可能会遇到该类型具有多个实例的情况。
关于C# 反射从类型中获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5303837/