C# 反射从类型获取对象
我有一个 Type 对象。 我想从这种类型中获取对象实例。 (只是为了使用该对象的 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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Activator.CreateInstance 就是您想要的。
编辑:根据您的编辑,您想要的
Type
扩展方法 (ToObject
) 实际上是上面的代码。它必须创建一个新对象,因为您无法确定源对象是否仍然存在,即使使用该类型,您也可能会遇到该类型具有多个实例的情况。Activator.CreateInstance is what you want.
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.)
没有办法做到这一点。原因之一是
GetType
将为同一类型的所有实例返回相同的Type
实例。您可以这样测试:
在这两个不同的字符串实例上调用
GetType
返回相同的Type
实例,因此显然不可能仅根据该实例取回其中一个实例类型
实例。There is no way to do that. One reason is that
GetType
will return the sameType
instance for all instances of the same type.You can test this like so:
Calling
GetType
on those two different string instances returns the sameType
instance, so it is clearly impossible to get one of them back based only on thatType
instance.