如何将 C# 8 中的默认 return 值标记为仅对 类 可为空?
How to mark a default return value in C# 8 as nullable for classes only?
我目前正在尝试将新的 C# 8.0 不可空引用类型功能应用于现有代码,但不知道如何修复以下数据反序列化方法中的 CS8603 警告:
T ReadOptional<T>() where T : IEntity, new()
{
if (ReadBoolean())
{
T instance = new T();
instance.Read(this); // IEntity method
return instance;
}
else
{
// CS8603 Possible null reference return.
return default;
}
}
如您所见,如果前面的布尔值为假,则该方法可能 return null
(类) / default
(structs),否则 returns 一个 T
实例,它可以是任何实现 IEntity
.
的实例
但是,我不能将 return 类型标记为 T?
,因为如果 T
是一个结构,它实际上不会 return null
,因为编译器错误 CS8627 正确抱怨:
// CS8627: A nullable type parameter must be known to be a value type or non-nullable
// reference type. Consider adding a 'class', 'struct', or type constraint.
T? ReadOptional<T>() where T : IEntity, new()
- 我无法通过确保
T
具有 class
约束来解决此问题,因为我还希望 struct
实例使用此方法(returning default
).
- 我无法使用具有
struct
约束的 T
创建重载,因为重载不能仅因约束而异。
- 我可以创建不同命名的方法,但这会破坏库接口,并且会破坏太多依赖于它的代码。
是否有任何语法可以在不破坏 returning default
结构实例的可能性的情况下修复不可为 null 的警告?
编辑:有一个稍微改进的解决方案 。
浏览 , I filled a gap in my knowledge about nullable reference types: There's a null-forgiving operator !
可以在此处为我修复警告:
T ReadOptional<T>() where T : IEntity, new()
{
if (ReadBoolean())
{
T instance = new T();
instance.Read(this); // IEntity method
return instance;
}
else
{
return default!; // <-- note the exclamation mark
}
}
我目前正在尝试将新的 C# 8.0 不可空引用类型功能应用于现有代码,但不知道如何修复以下数据反序列化方法中的 CS8603 警告:
T ReadOptional<T>() where T : IEntity, new()
{
if (ReadBoolean())
{
T instance = new T();
instance.Read(this); // IEntity method
return instance;
}
else
{
// CS8603 Possible null reference return.
return default;
}
}
如您所见,如果前面的布尔值为假,则该方法可能 return null
(类) / default
(structs),否则 returns 一个 T
实例,它可以是任何实现 IEntity
.
但是,我不能将 return 类型标记为 T?
,因为如果 T
是一个结构,它实际上不会 return null
,因为编译器错误 CS8627 正确抱怨:
// CS8627: A nullable type parameter must be known to be a value type or non-nullable
// reference type. Consider adding a 'class', 'struct', or type constraint.
T? ReadOptional<T>() where T : IEntity, new()
- 我无法通过确保
T
具有class
约束来解决此问题,因为我还希望struct
实例使用此方法(returningdefault
). - 我无法使用具有
struct
约束的T
创建重载,因为重载不能仅因约束而异。 - 我可以创建不同命名的方法,但这会破坏库接口,并且会破坏太多依赖于它的代码。
是否有任何语法可以在不破坏 returning default
结构实例的可能性的情况下修复不可为 null 的警告?
编辑:有一个稍微改进的解决方案
浏览 !
可以在此处为我修复警告:
T ReadOptional<T>() where T : IEntity, new()
{
if (ReadBoolean())
{
T instance = new T();
instance.Read(this); // IEntity method
return instance;
}
else
{
return default!; // <-- note the exclamation mark
}
}