[英]Generic throw function for non-nullable types
I am trying to convert an existing project to using nullable reference types properties using non-nullable properties during initialization .我试图在初始化期间使用不可为空的属性将现有项目转换为使用可空引用类型属性。
I am using this approach for getting properties which should exist:我正在使用这种方法来获取应该存在的属性:
public class Dog
{
private Person? _person;
public int Id { get; set; }
public string Name { get; set; }
public Person Person
{
get => _person ?? throw new InvalidOperationException(
$"Unset property {nameof(_person)}. You probably forgot to Include it");
set => _person = value;
}
}
But it's tedious to write this for almost every property, so I've tried to make a generic ThrowOrGet()
function:但是为几乎每个属性都写这个很乏味,所以我试图制作一个通用的
ThrowOrGet()
函数:
public static class Util
{
public static T ThrowOrGet<T>([AllowNull] T obj)
{
if (obj == null)
{
throw new InvalidOperationException(
$"Unset property {nameof(obj)}. You probably forgot to Include it");
}
return obj;
}
}
Which is used like this:这是这样使用的:
public class Dog
{
private Person? _person;
public int Id { get; set; }
public string Name { get; set; }
public Person Person
{
get => Util.ThrowOrGet(_person); ---> "Possible null reference return"
set => _person = value;
}
}
But the the function Util.ThrowOrGet(_person);
但是函数
Util.ThrowOrGet(_person);
now says that it's a possible null
reference return.现在说这是一个可能的
null
引用返回。 If I inline the function, it works as intended.如果我内联该函数,它将按预期工作。 Is there a way to make a generic function that does this?
有没有办法制作一个通用函数来做到这一点?
If you're only going to use ThrowOrGet
on reference types (which you should, as it doesn't make sense for value types), then you should declare it like this:如果你只打算在引用类型上使用
ThrowOrGet
(你应该这样做,因为它对值类型没有意义),那么你应该像这样声明它:
public static T ThrowOrGet<T>(T? obj) where T : class
{
if (obj == null)
{
throw new InvalidOperationException(
$"Unset property {nameof(obj)}. You probably forgot to Include it");
}
return obj;
}
This says that the function accepts a nullable argument, and always returns a non-nullable reference.这表示该函数接受一个可为空的参数,并始终返回一个不可为空的引用。 It's better to follow this pattern than rely on the attributes, as they're really just there for complex cases, which this is not.
遵循此模式比依赖属性更好,因为它们实际上只用于复杂情况,而事实并非如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.