可以知道/获取父类中的子类吗?我使用Autofac作为DI,而ILogger logger将由Autofac提供,所以logger不会是null(我没有在这里复制该代码以保持简短)

有许多child个类(在一个目录中),它们继承自Parent个抽象类.我想在父类中做一次"logger init"(干燥).当我获得logger.GetCurrentClassLogger<this>()对象时,我try 使用this关键字,但它似乎不正确,因为它不会构建.

以下是一个示例代码-


public ILogger GetCurrentClassLogger<T>() { return Log.ForContext<T>(); }

public class Parent() {
    protected Serilog.ILogger LoggerDefinedInParentClass;
    public Parent(Serilog.ILogger logger) {
        LoggerDefinedInParentClass = logger.GetCurrentClassLogger<Parent>();

        // Hoping to use <Child1> or <Child2> GetCurrentClassLogger<-child class->. Tried <this>, but it might not be right as the build fails
        //
    }

    public void ParentMethod1() {
        LoggerDefinedInParentClass.Information("Hello, ParentMethod1");
    }

    public void ParentMethod1() {
        LoggerDefinedInParentClass.Information("Hello, ParentMethod2");
    }
}

public class Child1() : Parent {
    public Child1(Serilog.ILogger logger): base(logger) {
    }

    public void ParentMethod1() {
        LoggerDefinedInParentClass.Information("Hello, Child1-1");
    }

    public void ParentMethod1() {
        LoggerDefinedInParentClass.Information("Hello, Child1-2");
    }
}

public class Child2() : Parent {
    public Child2(Serilog.ILogger logger): base(logger) {
    }

    public void ParentMethod1() {
        LoggerDefinedInParentClass.Information("Hello, Child2-1");
    }

    public void ParentMethod1() {
        LoggerDefinedInParentClass.Information("Hello, Child2-2");
    }
}

我希望打印日志(log)行,就好像它们来自Child1Child2个子元素的班级,但似乎弄不明白.

有谁有主意吗?提亚

推荐答案

存在接受类型为Log.ForContext的非泛型重载-您可以使用它:

LoggerDefinedInParentClass = Log.ForContext(this.GetType());

虽然通常的方法是使用框架提供的ILogger,并允许DI处理注入:

public abstract class Parent() {
    public Parent(ILogger logger){...}
}

public class Child1() : Parent {
    public Child1(ILogger<Child1> logger): base(logger) {
    }
}

Csharp相关问答推荐

如何从C#中有类.x和类.y的类列表中映射List(字符串x,字符串y)?

注册通用工厂的C# Dep注入

更改对象的旋转方向

如果属性名为xyz,我需要使用System.Text.Json修改字符串类型的值""<>

dotnet集合中内部数组的局部变量副本的用途是什么?'

如何在C#中使用正则表达式抓取用逗号分隔的两个单词?

Nuget包Serilog.Sinks.AwsCloudwatch引发TypeLoadExceptions,因为父类型是密封的

返回TyedResults.BadRequest<;字符串>;时问题详细信息不起作用

MongoDB.NET-将数据绑定到模型类,但无法读取整数值

从c#列表中删除额外的对象&对象&>从ASP.NET WebForm返回json响应

需要在重新启动ApplicartionPool或IIS后启动/唤醒API的帮助

如何从ASP.NET核心MVC视图和Blazor传递数据

Savagger使用Fastendpoint更改用户界面参数

按需无缝转码单个HLS数据段

为值对象编写自定义JsonConverter

C#Microsoft.CodeAnalysis.CSharp.Scriiting不等待并行.对于

如何在单击按钮后多次异步更新标签

Maui:更改代码中的绑定字符串不会更新UI,除非重新生成字符串(MVVM)

如何在C#.NET桌面应用程序中动态更改焦点工具上的后退 colored颜色

Xamarin中出错.表单:应用程序的分部声明不能指定不同的基类