我想创建一个具有type成员的泛型类T。T可以是类,可为空的类,结构或可为空的结构。所以基本上什么都可以。这是一个简化的示例,显示了我的问题:
#nullable enable
class Box<T> {
public T Value { get; }
public Box(T value) {
Value = value;
}
public static Box<T> CreateDefault()
=> new Box<T>(default(T));
}
Run Code Online (Sandbox Code Playgroud)
由于使用了新#nullable enable功能,我得到以下警告:Program.cs(11,23): warning CS8653: A default expression introduces a null value when 'T' is a non-nullable reference type.
这个警告对我来说很有意义。然后,我尝试通过?在属性和构造函数参数中添加来修复此问题:
#nullable enable
class Box<T> {
public T? Value { get; }
public Box(T? value) {
Value = value;
}
public static Box<T> CreateDefault()
=> …Run Code Online (Sandbox Code Playgroud) 在C#泛型方法中是否可以返回对象类型或Nullable类型?
例如,如果我有一个安全的索引访问器List,我想返回一个值,我可以稍后检查== null或使用或.HasValue().
我目前有以下两种方法:
static T? SafeGet<T>(List<T> list, int index) where T : struct
{
if (list == null || index < 0 || index >= list.Count)
{
return null;
}
return list[index];
}
static T SafeGetObj<T>(List<T> list, int index) where T : class
{
if (list == null || index < 0 || index >= list.Count)
{
return null;
}
return list[index];
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试将方法组合到一个方法中.
static T SafeGetTest<T>(List<T> list, int index)
{
if (list …Run Code Online (Sandbox Code Playgroud)