泛型函数和强制转换ref参数

时间:2018-11-29 09:21:24

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

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<MyModel>(responseContent, ref result);

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

1 个答案:

答案 0 :(得分:3)

这是因为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; }
}