c# - 如何在 .net 中使用反射获取对象名称?

标签 c# .net vb.net reflection

在 .net 中,我如何获取声明类型中的对象名称。例如……

public static void Main()
{
Information dataInformation =  new Information();
}

public class Inforamtion
{

//Constructor
public Inforamtion()
{

//Can I fetch name of object i.e. "dataInformation" declared in Main function
//I want to set the object's Name property = dataInformation here, because it is the name used in declaring that object.
}

public string Name = {get; set;}
}

最佳答案

就 CLR 而言,并没有真正确定对象名称的方法。这类信息(在某种程度上)存储在调试信息和程序集中,但不会在运行时使用。无论如何,您所指的对象只是内存中的一堆字节。它可以通过多个名称对它进行多次引用,因此即使您可以获得引用该对象的所有变量的名称,也无法以编程方式确定您要使用哪个变量。

长话短说:你不能那样做。

关于c# - 如何在 .net 中使用反射获取对象名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1653450/

相关文章:

c# - 命名空间 bla 已经包含(我的部分)类的定义

C# 与 CLI 进程交互 - StandardInput 停止执行

c# - 我的 MVC3 密码处理是否足够

c# - AUTOINCREMENT 不适用于 OleDbCommand

asp.net - 我的 pay pal 按钮不会链接到 paypal。它只刷新页面,为什么?

c# - 此关系的哪一部分 WillCascadeOnDelete(true)?

c# - 只序列化一个类的一个属性

c# - 文本框只读

vb.net - 我需要担心创建的任务数量吗?

.net - 使用 [Type].Parse 还是 C[Type] 更好