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

C#中如何将对象转换为带泛型类型的Result<T>类?

解决方案

方法一:定义非泛型接口(推荐)

如果可以修改Result<T>的定义,最安全高效的方式是给它加一个非泛型接口,通过接口统一访问Value属性:

  1. 定义非泛型接口:
public interface IResult
{
    object? Value { get; }
}
  1. 修改泛型类实现接口:
public class Result<T> : IResult where T : class, new()
{
    public T? Value { get; set; }

    // 显式实现接口,避免和泛型Value属性冲突
    object? IResult.Value => Value;
}
  1. 转换和访问:
object? funcValue = await GetResponse().Value;

if (funcValue is IResult response)
{
    var res = response.Value;
    // 若需要可将res转换为具体类型
}

方法二:反射(无法修改Result时使用)

如果不能修改泛型类的定义,用反射来检测类型并获取属性值:

object? funcValue = await GetResponse().Value;

var resultType = funcValue?.GetType();
// 准确判断是否为Result<>的实例,避免命名冲突
if (resultType != null && resultType.IsGenericType && 
    resultType.GetGenericTypeDefinition() == typeof(Result<>))
{
    var valueProperty = resultType.GetProperty(nameof(Result<object>.Value));
    var res = valueProperty?.GetValue(funcValue);
    // res即为Value属性的值,类型为object
}

方法三:动态类型(不推荐,仅临时方案)

用dynamic跳过编译时类型检查,但会丢失类型安全,且性能略差:

object? funcValue = await GetResponse().Value;

if (funcValue?.GetType().IsGenericType == true &&
    funcValue.GetType().GetGenericTypeDefinition() == typeof(Result<>))
{
    dynamic dynamicResult = funcValue;
    var res = dynamicResult.Value;
    // res为运行时实际类型,编译时无类型检查
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 18:34:50