简体   繁体   中英

How to get caller methods name?

Is there a way to get all caller of C# method ie:

public string Caller(string str)
{      
  Customer cust = new Customer();
  cust.Firstname = "Peter";
  cust.LastName = "Beamer";
  string t = getName(cust);
  return t;
}

private string getName(Customer customer)
{
  return customer.Firstname +" "+ customer.LastName;
}

would return: Caller.

All I can get now is method body text using EnvDTE.CodeFunction . Maybe there is a better way to achieve it than trying to parse this code.

Note: I don't want to get current method's calling method name. I want that If I give name of the method then It will return passed method's calling methods name.

new StackFrame(1, true).GetMethod().Name

Note that in release builds the compiler might inline the method being called, in which case the above code would return the caller of the caller, so to be safe you should decorate your method with:

[MethodImpl(MethodImplOptions.NoInlining)]

source: https://stackoverflow.com/a/1310148/1714342

While it is certainly possible to do it using StackFrame as wudzik points out, why would you need to do this?

This is a design smell. If your code has to have knowledge about its caller, something is wrong with your design. Every such dependency should be abstracted out of your class model.

不是很积极我理解你在问什么,因为似乎没有人确定什么应该返回“来电者”...但是,或许CallerMemberNameAttribute可能会有所帮助?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM