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

如何在C#中通过OneOf从函数获取输入变量的实际值

问题解决:根据实例类型调用对应处理函数

核心错误修正(使用OneOf包)

你当前代码的问题在于Match委托里的参数传递错误:Match方法会把匹配到的具体实例传递给委托的参数(比如ClassA => ...里的ClassA就是你传入的Paul实例),但你错误传入了原始的input参数。正确写法如下:

public static string GetName(OneOf<ClassA, ClassB, ClassC> input)
{
    return input.Match(
        classAInstance => doSomethingWithA(classAInstance),
        classBInstance => doSomethingWithB(classBInstance),
        classCInstance => doSomethingWithC(classCInstance)
    );
}

这里的classAInstance就是对应类型的Paul实例,直接传递给处理函数即可,无需使用input.Value。


无需OneOf包的替代方案

方案1:switch模式匹配

利用C#原生模式匹配,直接根据类型分发逻辑:

public static string GetName(object input)
{
    return input switch
    {
        ClassA a => doSomethingWithA(a),
        ClassB b => doSomethingWithB(b),
        ClassC c => doSomethingWithC(c),
        _ => throw new ArgumentException("参数类型不支持")
    };
}

方案2:多态实现(更符合面向对象设计)

如果可以修改ClassA/ClassB/ClassC的代码,定义统一接口让它们实现,将逻辑内聚到类中:

// 定义统一接口
public interface INameProvider
{
    string GetName();
}

// 每个类实现接口
public class ClassA : INameProvider
{
    public string GetName() => doSomethingWithA(this);
}

public class ClassB : INameProvider
{
    public string GetName() => doSomethingWithB(this);
}

public class ClassC : INameProvider
{
    public string GetName() => doSomethingWithC(this);
}

调用时直接使用实例方法,无需额外分发函数:

Name = Paul.GetName();

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 07:52:36