在.NET(最初是.NET CF)中,如何获取对象的完整地址和名称?
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Button myButton = new Button();
MessageBox.Show(GetFullName(myButton));
}
string GetFullName(object obj)
{
string path = null;
// should retrieve the 'WindowsFormsApplication1.Form2.myButton' , but how?
return path;
}
}
}
答案 0 :(得分:2)
// should retrieve the 'WindowsFormsApplication1.Form2.myButton' , but how?
那是不可能的。
C#中的对象驻留在托管堆上的某个位置(它甚至可以移动),并通过对它的引用来标识。可以有许多对同一对象的引用,但是从对象到引用它的任何地方都没有“后退指针”。
class Program
{
int number;
public Program next;
private static Program p1 { number = 1 };
private static Program p2 { number = 2, next = p1 }
private static int Main(int argc, string[] argv)
{
p2.DoStuff(p2);
}
void DoStuff(Program p)
{
// In here, the program with m_Number = 1 can be reached
// as p1, p.next, p2.next and this.next. All of them are
// references to the same object.
}
}
答案 1 :(得分:2)
就像其他人所说的那样,myButton在你的例子中是一个变量,所以它没有像通常那样的类成员的名字。但是,您可以尝试这样的事情(注意我在按钮上设置了Name属性并将参数更改为Control)...
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Button myButton = new Button();
myButton.Name = "myButton";
MessageBox.Show(GetFullName(myButton));
}
string GetFullName(Control ctl)
{
return string.Format("{0}.{1}", this.GetType().FullName, ctl.Name);
}
}
}