This article is a mirror article of machine translation, please click here to jump to the original article.

View: 29154|Reply: 2

[Source] .NET/C# attributes CallerMemberName, CallerFilePath, CallerLineNumber

[Copy link]
Posted on 8/11/2021 9:45:56 AM | | | |
Three Attributes were introduced in .Net 4.5: CallerMemberName, CallerFilePath, and CallerLineNumber. With the help of the compiler, you can get the name of the calling function (to be precise, it should be a member), the call file and the call line number.

Documentation:https://docs.microsoft.com/en-us ... membernameattribute

You can also use StackTrace and StackFrame objects to get them, but with this feature, we can get them more conveniently.

StackTrace: Represents a stack trace, which is an ordered collection of one or more stack frames.

StackFrame: Provides information about the StackFrame (a function call in the call stack that represents the current thread).

Previously, I used AOP to get the caller's method name through StackTrace, and the code is as follows:


Using the feature, the test code is as follows:

Renderings:



(End)




Previous:Maven updatePolicy snapshot update policy
Next:Java byte[] and InputStream are converted to each other
 Landlord| Posted on 11/27/2022 9:09:56 PM |
 Landlord| Posted on 11/27/2022 10:35:47 PM |
Get the current method name from an asynchronous function?

The hyperlink login is visible.

C# 5 adds caller information properties, which may give you more of what you're looking for. Note that these insert the appropriate information at compile time into the calling site, rather than using runtime information. More limited functionality (obviously you don't get the full call stack), but much faster.





Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com