登录C#时,如何学习调用当前方法的方法的名称?我知道所有这些System.Reflection.MethodBase.GetCurrentMethod(),但我想在堆栈跟踪中向下迈出一步.我考虑过解析堆栈跟踪,但我希望找到一种更清晰,更明确的方法,比如Assembly.GetCallingAssembly()方法.
我想通过反射机制获取属性名称.可能吗?
更新:我有这样的代码:
public CarType Car
{
get { return (Wheel) this["Wheel"];}
set { this["Wheel"] = value; }
}
Run Code Online (Sandbox Code Playgroud)
因为我需要更多这样的属性,我想做这样的事情:
public CarType Car
{
get { return (Wheel) this[GetThisPropertyName()];}
set { this[GetThisPropertyName()] = value; }
}
Run Code Online (Sandbox Code Playgroud) 我正在使用NLog并遵循建议的模式,在每个类上都有一个日志声明,以便能够跟踪哪个类/方法已写入日志.我发现每次日志写入都有一点顶级"堆栈跟踪"非常有用.
我的代码看起来像这样:
class SomeClass {
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
void DoStuff() {
logger.Debug("stuff"); }
}
Run Code Online (Sandbox Code Playgroud)
我最近要求我的单个项目写入3个单独的日志文件,为此,我添加了多个记录器和目标,如下所示:https://stackoverflow.com/a/21711838/191206
但是,现在在我的日志文件中,我丢失了类级名称.它现在只写我在NLog.config中指定的日志名称.我已经考虑过简单地通过调用来添加方法名称
System.Reflection.MethodBase.GetCurrentMethod(); // use Name property
Run Code Online (Sandbox Code Playgroud)
或像这样使用反射中的其他东西
但是,我想知道NLog是否有内置的东西我错过了?Debug()方法我只看到编写字符串的能力,带参数和可选的格式化..
这是内置到NLog?
有一些属性(例如CallerMemberNameC# 中的属性)非常方便,特别是对于日志记录目的。每个人(或者至少是我)似乎都缺乏的是CallerClassName,我们可以轻松地记录这样的内容,而无需显式传递this或带有类名的字符串:
MyClass.MyMethod 执行期间发生异常
是否有任何限制可以让我们更容易了解方法而不是类,或者它只是我们可以要求添加的缺失功能?
假设我有一个父类和一个子类:
public abstract class Parent
{
public string GetParentName()
{
return GetType().Name;
}
}
public class Child : Parent
{
public string GetChildName()
{
return GetType().Name;
}
}
Run Code Online (Sandbox Code Playgroud)
截至目前,GetParentName()和GetChildName()都将返回Child.
但是,在我的场景中,我想获取声明方法的类的名称.
因此GetChildName()应返回Child但GetParentName()应返回Parent.
这有可能吗?
注意:
我知道我可以使用GetType().BaseType.Name但这不起作用,因为层次结构可能很复杂.
我有两个课程如下:
第一:
class Class1
{
private void Method1()
{
var obj=new TestClass();
obj.TestMethod1();
}
}
Run Code Online (Sandbox Code Playgroud)
第二个:
class TestClass
{
public void TestMethod1()
{
TestMethod2();
}
private void TestMethod2()
{
//get the calling class
}
}
Run Code Online (Sandbox Code Playgroud)
当Class1.Method1调用TestClass.TestMethod1这反过来又来电TestClass.TestMethod2,我想的完全限定类名Class1内TestClass.TestMethod2.我看过这个链接,但我想我会得到TestClass.TestMethod1方法名和TestClass类名.我怎样才能获得调用类名称?
可能重复:
C#中的反射:如何获取调用方法名称和类型?
假设我有两个类:
public class Foo {
public Foo() {
Bar.Pirate();
}
}
public static class Bar {
public static void Pirate() {
Type callingClassType = ...
}
}
Run Code Online (Sandbox Code Playgroud)
在内部Pirate(),如何获取调用Type的class(Foo)Pirate()?
c# ×7
.net ×4
reflection ×4
attributes ×1
inheritance ×1
logging ×1
nlog ×1
properties ×1
stack-trace ×1