I created the following extension:
public static class StackTraceExtensions
{
public static string Callers(this StackTrace trace)
{
return string.Join(" < ", trace.GetFrames().Select(sf => sf.GetMethod().DeclaringType.Name "." sf.GetMethod().Name));
}
}
but calling GetMethod()
every time isn't a good solution. I looked for some way to create an intermediate variable the way the LINQ .Select
function it does.
.Select
is available only for IEnumerable
and is intended for multiple values, therefore I developed yet another extension, this time for any object:
public static class ObjectExtensions
{
public static TResult Self<TSource, TResult>(this TSource source, Func<TSource, TResult> selector) => selector(source);
}
This extension could be used as follows:
public static class StackTraceExtensions
{
public static string Callers(this StackTrace trace)
{
return string.Join(" < ", trace.GetFrames().Select(sf => sf.GetMethod().Self(mb => $"{mb.DeclaringType.Name}.{mb.Name}")));
}
}
It allows me to deal here with the intermediate mb
"variable".
Is there some standard extension that does the same so I don't need to create my own?
CodePudding user response:
You can first select the method and then use it in a subsequent Select
:
return string.Join(" < ", trace.GetFrames()
.Select(sf => sf.GetMethod())
.Select(m => $"{m.DeclaringType.Name}.{m.Name}"));