简体   繁体   English

C#反射从类型获取对象

[英]C# reflection get object from type

I have a Type object. 我有一个Type对象。 I want to get the object isntance from this type. 我想从这种类型得到对象的重要性。 (just to use the ToString() method from this object). (只是为了使用此对象的ToString()方法)。 see: 看到:

    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 is what you want. Activator.CreateInstance是您想要的。

Type givenType;
var obj = Activator.CreateInstance(givenType);
...
var obj = Activator.CreateInstance(givenType) as GivenType;

EDIT: Based on your edits, the extension method on Type you want ( ToObject ) is effectively the code above. 编辑:根据您的编辑,所需TypeToObject )上的扩展方法ToObject是上面的代码。 It must create a new one because you can't be certain the source object still exists and even with the type, you could hit a scenario where that type has multiple instances. 它必须创建一个新对象,因为您不能确定源对象仍然存在,即使使用该类型,也可能遇到该类型具有多个实例的情况。

You cannot get the instance back. 您无法找回实例。 The type is shared between all the instances, so what you want is impossible. 该类型在所有实例之间共享,因此您想要的是不可能的。

For example: if you know that something is an integer, you don't know which exactly value it has. 例如:如果您知道某物是整数,则不知道其确切值。 (Integer is your type, value is a concrete instance.) (整数是您的类型,值是一个具体实例。)

There is no way to do that. 没有办法做到这一点。 One reason is that GetType will return the same Type instance for all instances of the same type. 原因之一是GetType将为相同Type的所有实例返回相同的Type实例。

You can test this like so: 您可以这样测试:

// this will print "True"
Console.WriteLine(object.ReferenceEquals("one".GetType(), "two".GetType()));

Calling GetType on those two different string instances returns the same Type instance, so it is clearly impossible to get one of them back based only on that Type instance. 在这两个不同的字符串实例上调用GetType将返回相同的Type实例,因此显然不可能仅基于该Type实例取回其中的一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM