[英]How to assign a value to a property of an object only if that object is not null in c#
Homework homework = isposted ? new Homework() : null;
If(homework != null)
{
homework.Id = 3;
homework.Name = "Draw an Apple";
}
// Why can't I use like this ?
homework ? .Id = 3;
homework ? .Name = "Draw an Apple"; // instead of checking for if condition
// Is there any way to minimise the code length?` //是否有任何方法可以最小化代码长度?
you can use object initialization to shorten it a fair bit 您可以使用对象初始化将其缩短一点
Homework homework = isposted
? new Homework
{
Id = 3,
Name = "Draw an Apple"
} : null;
Actually, I had an object like Homework homework = isposted ?
实际上,我有一个类似Homework homework = isposted的对象。 oldHomework : null;
oldHomework:null;
I would assume you want a copy of the oldHomework
, then you can use this code below 我假设您想要
oldHomework
的副本,那么您可以在下面使用此代码
Homework homework = isposted
? new Homework
{
Id = oldHomework.Id,
Name = oldHomework.Name
} : null;
You can't assign a value to an object that is NULL. 您不能将值赋给NULL的对象。 The
?
?
is for reading properties, not setting them. 用于读取属性,而不是设置属性。
var x = homework.Id; // Will throw an error if homework is NULL
var y = homework?.Id; // Will be NULL if homework is NULL
For setting properties, you definitely want to check for NULL and then only set them if it is not NULL. 对于设置属性,您肯定要检查NULL,然后仅在不为NULL的情况下进行设置。 Just exactly the way you're doing it is perfect.
恰恰是您执行操作的方式是完美的。
There is no such operator, the closest way of achieving what you wanted I could think of is by using an extension method like this: 没有这样的运算符,实现您想要的最接近的方法是使用如下扩展方法:
public static class Extensions
{
public static void IfNotNull<T>(this T obj, Action<T> action)
{
if (obj == null)
return;
action(obj);
}
}
Homework homework = isposted ? new Homework() : null;
homework.IfNotNull(h => h.Id = 3);
homework.IfNotNull(h => h.Name = "Draw an Apple");
However the extension method still uses an if
statement. 但是,扩展方法仍使用
if
语句。 It doesn't need to be an extension method. 它不必是扩展方法。
To be honest I'd never use such solution in a real project.
老实说, 我永远不会在实际项目中使用这种解决方案 。 You should not sacrifice code readability just to use fewer lines of code, this solution doesn't even improve performance.
您不应该仅仅为了减少代码行而牺牲代码的可读性,该解决方案甚至不能提高性能。 I only wanted to share the closest solution I could find for your question.
我只想分享我可以为您的问题找到的最接近的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.