C# 内联“;如果是:在一次调用中获取并测试一个值
我有以下几点C# 内联“;如果是:在一次调用中获取并测试一个值,c#,.net-4.5,C#,.net 4.5,我有以下几点 IPublishedContentProperty propTitle; // the type is not nullable // Compiles, 2 GetProperty calls var title = x.GetProperty("title").HasValue ? x.GetProperty("title").Value : null; // Does not compile, 1 GetProperty call title = (propTit
IPublishedContentProperty propTitle; // the type is not nullable
// Compiles, 2 GetProperty calls
var title = x.GetProperty("title").HasValue ? x.GetProperty("title").Value : null;
// Does not compile, 1 GetProperty call
title = (propTitle=x.GetProperty("title") && propTitle.HasValue) ?propTitle.Value:null;
假设GetProperty
是一个耗时的操作,我只想调用这个方法一次。
因此,第一行是在编译时。第二个不是,而是我想要实现的
限制条件:
if
块.HasValue
并不意味着该类型可为null,它只是一个具有此类bool属性的类型
未编译的原因:
&&
在=
之前进行评估。而&&
显然不是这些类型上的有效操作
这可以用一对支架固定。然后可以将.HasValue
应用于赋值结果(即已赋值的对象或值)
Edit:通过定义扩展方法,可以使此表达式更短、更可读。如果您在多个地方使用该构造,那么它还将减少冗余和混乱
例如:
namespace Your.Project.Helpers
{
public static class PropertyHelper
{
// use actual type (or interface)
public static string GetValueOrDefault(this Property p)
{
return p.HasValue ? p.Value : null;
}
}
}
用法:
using Your.Project.Helpers;
...
var title = x.GetProperty("title").GetValueOrDefault();
您确实意识到您的代码相当于
var title=x.GetProperty(“title”)
?您可以编写扩展方法,将x.GetProperty内部保存到变量中,然后使用条件?没有扩展方法@Heinzi,不是真的,您忘记了。Value@Serge对不起,是我的错,它看起来像是x.GetProperty
返回了一个可为null的值类型,但它显然有所不同。@Heinzi:很好,不是返回的可为null的类型。是的!很好的建议,很简单!遗憾的是,propTitle
应该在该代码之前声明为一个单独的变量。。。有没有办法内联声明变量?请参阅我的。。。extensiongood主意不错,但我的案例太具体了,没有在其他地方使用,因此无法真正实现扩展方法。然而,总的来说,这是一个好主意。我的问题是,我的cshtml页面不需要重新编译,但是一个扩展方法需要一个,所以要替换DLL。。。对这样的小事来说更复杂)
using Your.Project.Helpers;
...
var title = x.GetProperty("title").GetValueOrDefault();