看测试代码,在一个类文件中定义两个类: public class TestA { public void Foo() { Form1.Test(); } } public class TestB { public void Foo() { Form1.Test(); } } 主窗口的文件: public partial class Form1 : Form { public static void Test() { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); var f = st.GetFrame(1); var m = f.GetMethod(); MessageBox.Show(m.ReflectedType.Name); } public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { TestA a = new TestA(); TestB b = new TestB(); a.Foo(); b.Foo(); } } 点击按钮,将依次显示:TestA和TestB对应调用者的类名。
可以的.你可以通过反射功能来实现.using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Reflection; using System.Diagnostics; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { MyTest t = new MyTest(); t.add(1); } } public class MyTest { public void add(int i) { i++;
StackTrace ss = new StackTrace(true); Type t = ss.GetFrame(1).GetMethod().DeclaringType; MessageBox.Show(t.FullName);
{
public void Foo()
{
Form1.Test();
}
} public class TestB
{
public void Foo()
{
Form1.Test();
}
}
主窗口的文件: public partial class Form1 : Form
{
public static void Test()
{
System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
var f = st.GetFrame(1);
var m = f.GetMethod();
MessageBox.Show(m.ReflectedType.Name);
}
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
TestA a = new TestA();
TestB b = new TestB();
a.Foo();
b.Foo();
}
}
点击按钮,将依次显示:TestA和TestB对应调用者的类名。
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
MyTest t = new MyTest();
t.add(1);
}
} public class MyTest
{ public void add(int i)
{
i++;
StackTrace ss = new StackTrace(true);
Type t = ss.GetFrame(1).GetMethod().DeclaringType;
MessageBox.Show(t.FullName);
}
}
}