gpt4 book ai didi

c# - 在 C# 中使用类型作为函数参数创建通用对象

转载 作者:太空宇宙 更新时间:2023-11-03 19:39:44 25 4
gpt4 key购买 nike

我正在尝试创建一个通用函数来使用 Newtonsoft 解析我的 json 结果:

private T ParseResult<T>(string queryResult)
{
Result res = JsonConvert.DeserializeObject<Result>(queryResult);

if (res.Success == 1)
{
try
{
return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(res.data));
}
catch (Exception)
{
return default(T);
}
}
return default(T);
}

如果成功或解析有问题,我想返回一个空对象,无论 T 是什么(当前列表或只是自定义对象)。

我的问题是当前的解决方案返回 null 而不是空对象。我怎样才能实现返回值永远不会为空。

最佳答案

不管这是对还是错的做法。问题是 default(T) 将为 type 返回 default,对于 Reference Types。如果你想要一个“空对象”(新对象)那么你将不得不使用new constraint新建它(实例化它)

示例

private T ParseResult<T>(string queryResult) where T : new()
{

...

return new T();

}

注意:尽管有一些注意事项

new constraint (C# Reference)

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.


其他资源

default value expressions (C# programming guide)

A default value expression default(T) produces the default value of a type T. The following table shows which values are produced for various types:

  • Any reference type : null
  • Numeric value type : 0
  • bool : false
  • char : \0
  • enum : The value produced by the expression (E)0, where E is the enum identifier.
  • struct : The value produced by setting all value type fields to their default value and all reference type fields to null.
  • Nullable type : An instance for which the HasValue property is false and the Value property is undefined.

关于c# - 在 C# 中使用类型作为函数参数创建通用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55256794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com