C# reflection get object from type
I have a Type object. I want to get the object isntance from this type. (just to use the ToString() method from this object). 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.
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. 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.
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.
精彩评论