代码之家  ›  专栏  ›  技术社区  ›  willeM_ Van Onsem

获取在C中调用该方法的实例#

  •  14
  • willeM_ Van Onsem  · 技术社区  · 15 年前

    我正在寻找一个算法,可以得到的对象,调用该方法,在该方法。

    例如:

    public class Class1 {
    
        public void Method () {
            //the question
            object a = ...;//the object that called the method (in this case object1)
            //other instructions
        }
    
    }
    
    public class Class2 {
    
        public Class2 () {
            Class1 myClass1 = new Class1();
            myClass1.Method();
        }
    
        public static void Main () {
            Class2 object1 = new Class2();
            //...
        }
    
    }
    

    5 回复  |  直到 9 年前
        1
  •  -10
  •   Brian    15 年前

    显然,我不知道你的具体情况,但这真的似乎你需要重新考虑一下你的结构。

    如果构造了适当的继承,这很容易做到。

    考虑查看从抽象类继承的抽象类和类。你甚至可以用接口来完成同样的事情。

        2
  •  16
  •   Tracker1    13 年前

    下面是一个如何做到这一点的例子。。。

    ...
    using System.Diagnostics;
    ...
    
    public class MyClass
    {
    /*...*/
        //default level of two, will be 2 levels up from the GetCaller function.
        private static string GetCaller(int level = 2)
        {
            var m = new StackTrace().GetFrame(level).GetMethod();
    
            // .Name is the name only, .FullName includes the namespace
            var className = m.DeclaringType.FullName;
    
            //the method/function name you are looking for.
            var methodName = m.Name;
    
            //returns a composite of the namespace, class and method name.
            return className + "->" + methodName;
        }
    
        public void DoSomething() {
            //get the name of the class/method that called me.
            var whoCalledMe = GetCaller();
            //...
        }
    /*...*/
    }

    贴这个,因为我花了一段时间才找到我要找的东西。我在一些静态记录器方法中使用它。。。

        3
  •  2
  •   Teun D    15 年前

    您可以在代码中找到当前的堆栈跟踪并向上走一步。 http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx

    但正如下面的注释所述,这将得到调用您的方法和类,而不是实例(如果有实例,当然可能是静态的)。

        4
  •  -1
  •   user270350 user270350    15 年前

    或者将对象作为方法参数传递。

    public void Method(object callerObject)
    {
    ..
    }
    

    并调用方法:

    myClass.Method(this);
    

    你好,弗洛里安

        5
  •  -1
  •   Morfildur    15 年前

    会的 非常 糟糕的风格

    a) 这会破坏封装
    b) 在编译时不可能知道调用对象的类型,因此无论以后对该对象做什么,它都可能不起作用。
    c) 如果只将对象传递给构造函数或方法,会更容易/更好,如:

    Class1 c1 = new Class1(object1);