C#reflection从类型中获取对象

Rod*_*lfo 1 c# reflection

我有一个Type对象.我想从这种类型获得对象isntance.(只是使用此对象的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Aus*_*nen 10

Activator.CreateInstance就是你想要的.

Type givenType;
var obj = Activator.CreateInstance(givenType);
...
var obj = Activator.CreateInstance(givenType) as GivenType;
Run Code Online (Sandbox Code Playgroud)

编辑:根据您的编辑,Type您想要(ToObject)的扩展方法实际上是上面的代码.它必须创建一个新的,因为您不能确定源对象是否仍然存在,即使使用该类型,您也可以遇到该类型具有多个实例的场景.