You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将HandleUnknownType静态方法移至基类以减少代码重复?

解决方案

思路一:给基类静态方法传递子类名称参数

把基类的HandleUnknownType改成带参数的静态方法,让子类调用时传入自己的类名(用nameof获取),这样基类就能正确输出调用方的类名:

基类代码:

public class MapperBase
{
    protected static PageComponent HandleUnknownType(object value, string mapperClassName)
    {
        throw new ArgumentException($"{mapperClassName} - failed to map object of type {value.GetType()}. Component={nameof(value)}");
    }
}

子类调用时:

public class ComponentMapper : MapperBase
{
    public static PageComponent Map(object value)
    {
        return value switch
        {
            _ => HandleUnknownType(value, nameof(ComponentMapper)),
        };
    }
}

思路二:使用泛型基类绑定子类类型

定义泛型基类,让子类继承时把自身类型作为泛型参数传入,基类通过typeof(T)获取子类名称,不用额外传参:

基类代码:

public class MapperBase<TMapper> where TMapper : class
{
    protected static PageComponent HandleUnknownType(object value)
    {
        string mapperClassName = typeof(TMapper).Name;
        throw new ArgumentException($"{mapperClassName} - failed to map object of type {value.GetType()}. Component={nameof(value)}");
    }
}

子类继承时绑定自身:

public class ComponentMapper : MapperBase<ComponentMapper>
{
    public static PageComponent Map(object value)
    {
        return value switch
        {
            _ => HandleUnknownType(value),
        };
    }
}

思路三:子类定义静态类名字段(可选)

如果觉得传参麻烦,可以在每个子类里定义一个静态常量存储类名,基类方法直接读取这个字段(需要确保所有子类都遵循这个约定):

基类代码:

public class MapperBase
{
    protected static PageComponent HandleUnknownType(object value, string mapperClassName)
    {
        throw new ArgumentException($"{mapperClassName} - failed to map object of type {value.GetType()}. Component={nameof(value)}");
    }
}

子类代码:

public class ComponentMapper : MapperBase
{
    private const string _mapperName = nameof(ComponentMapper);

    public static PageComponent Map(object value)
    {
        return value switch
        {
            _ => HandleUnknownType(value, _mapperName),
        };
    }
}

这几个方案都能保持HandleUnknownType的静态特性,同时让错误信息里显示实际调用的子类名称,不用实例化对象。

内容的提问来源于stack exchange,提问作者I am not Fat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 19:35:26