【问题标题】:Generic functions and cast ref parameter泛型函数和 cast ref 参数
【发布时间】:2019-05-01 07:27:52
【问题描述】:
public void ResponseHandler<T>( string responseContent, ref Result<T> result)
    where T : IServiceModel
{
    var respModel = responseContent.FromJson<OrderResponse>();
    if (respModel.Status.Equals(_innerConfig.SuccessTradeStatus, StringComparison.OrdinalIgnoreCase))
    {
        result.IsSuccess = true;
        result.Data.TradeNo = respModel.Transaction_id;// CAN NOT resolve symbol TradeNo   
    }
   ...
}

public class Result<T> : Result
{
    public T Data { get; set; }
}

public class MyModel:IServiceModel
{
    public string TradeNo  { get; set; }
}
public interface IServiceModel
  {
  }

用法:ServiceProvider.ResponseHandler&lt;MyModel&gt;(responseContent, ref result);

问题是我无法获取属性TradeNo, 我找到了另一个线程:Generic functions and ref returns in C# 7.0 但不确定我的代码是否存在同样的问题。 有什么建议吗?谢谢。 :)

【问题讨论】:

  • 欢迎来到 Stack Overflow。 TradeNo 在哪里声明?您能否提供一个minimal reproducible example,以便我们可以自己重现问题,以及所有相关类型? (您确定这与ref 参数有关吗?不清楚为什么这是ref 参数,因为您没有更改result 变量本身的值。)
  • 您无法访问 TradeNo 属性,因为 ResponseHandler&lt;T&gt; 不知道它正在处理的类型
  • @NitinSawant 任何铸造方法?
  • MyModel 没有在您显示的代码中实现IServiceModel,因此您甚至无法使用Result&lt;MyModel&gt; 调用ResponseHandler。即使它确实实现了ISerivceModel,您的方法也声称能够处理any IServiceModel 类型的结果。也许它应该是非通用的? public void ResponseHandler(string responseContent, Result&lt;MyModel&gt; model)?

标签: c# generics pass-by-reference c#-7.0


【解决方案1】:

这是因为Data 的类型是T

public class Result<T> : Result
{
    public T Data { get; set; }
}

T 的唯一约束是 where T : IServiceModel

如果您需要访问TradeNo,您需要将T 限制为MyModel 或将此属性添加到IServiceModel

public interface IServiceModel
{
    string TradeNo  { get; set; }
}

【讨论】:

    猜你喜欢
    • 2018-01-27
    • 2020-06-09
    • 1970-01-01
    • 2018-05-21
    • 2020-11-10
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    相关资源
    最近更新 更多