如何在方法中返回T类型或null?

问题描述 投票:0回答:4

我需要一个返回未指定类型或null的类的方法。

我需要它来处理API请求,例如,我正在请求一个文件,例如,一个图像和另一个文件(例如视频),为此我需要不同的类型。如果找不到图像/视频,我想返回null。

我已经尝试过Nullables,但是我可能用了错误的方式。

T? SendRequest<T?>(string pathOnServer)
{
    HttpResponseMessage response = SendTheRequest(pathOnServer);
    if(response.IsSuccessStatusCode)
        return JsonConvert.DeserializeObject<T>(response.Content.ReadAsStringAsync().Result);
    else
        return null;
}
c# null nullable
4个回答
1
投票

如果您不想将T约束为struct或class。您可以尝试

return default;

如果T为字符串或任何引用类型,则将返回null。


0
投票

很简单。

您只需要将方法限制为必须返回即可。

返回未指定类型或为null的类。

即T SendReuest(字符串pathOnServer),其中T:class

作为类,可以自动将其设为所有需要的空值。您只需要将T限制为CLASS,就可以了。


0
投票

您可以简单地使用where T : class

T SendRequest<T>(string pathOnServer) where T : class
        {
            HttpResponseMessage response = SendTheRequest(pathOnServer);
            if (response.IsSuccessStatusCode)
                return JsonConvert.DeserializeObject<T>(response.Content.ReadAsStringAsync().Result);
            else
                return null;
        }

-1
投票

检查此代码。代替不可为空的泛型类型,您需要使用不可为空的泛型类型。并返回可为空的T?

T? SendRequest<T>(string pathOnServer)
    where T : struct
{
    HttpResponseMessage response = SendTheRequest(pathOnServer);
    if(response.IsSuccessStatusCode)
        return JsonConvert.DeserializeObject<Nullable<T>>(response.Content.ReadAsStringAsync().Result);
    else
        return null;
}

PS:由于您没有提供minimum reproducible example,所以不确定代码是否有效。

© www.soinside.com 2019 - 2024. All rights reserved.