Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 4.0 旧编译器的空安全取消引用运算符?_C# 4.0 - Fatal编程技术网

C# 4.0 旧编译器的空安全取消引用运算符?

C# 4.0 旧编译器的空安全取消引用运算符?,c#-4.0,C# 4.0,我有一个旧的编译器服务器(VS 2010),它显然不能编译这样的指令: var result = a?.b()?.c?.d; 我可以用别的方法吗?是否可以通过表达式树执行此操作?例如,像这样: var result = NullSafe(()=> a.b().c.d); 在它成为一种语言特性之前,有很多人尝试过这样做。现在要找到参考文献有点困难,但是你可以知道如何做到,为什么不那么容易 例如,看起来很简单: public static R NullSafe<T, R>(th

我有一个旧的编译器服务器(VS 2010),它显然不能编译这样的指令:

var result = a?.b()?.c?.d;
我可以用别的方法吗?是否可以通过表达式树执行此操作?例如,像这样:

var result = NullSafe(()=> a.b().c.d);

在它成为一种语言特性之前,有很多人尝试过这样做。现在要找到参考文献有点困难,但是你可以知道如何做到,为什么不那么容易

例如,看起来很简单:

public static R NullSafe<T, R>(this T obj, Func<T, R> f) where T : class
{
       return obj != null ? f(obj) : default(R);
}
但它不适用于值类型。这将使用EqualityComparer:

public static TOut NullSafe<TIn, TOut>(this TIn obj, Func<TIn, TOut> memberAction)
{
    //Note we should not use obj != null because it can not test value types and also
    //compiler has to lift the type to a nullable type for doing the comparision with null.
    return (EqualityComparer<TIn>.Default.Equals(obj, default(TIn))) 
                         ? memberAction(obj) 
                         : default(TOut);
}

不过,至少可以说,实现有点复杂

创建一个扩展名method@Nkosi不是那么简单。当时人们确实创建了这样的扩展方法,可以接收表达式。它需要一点工作,以使一切都直和覆盖边缘的情况下?一些例子将帮助我理解我应该如何“创建”它。值得注意的是,如果你有一个代码块通过一个链中的许多属性/方法,那么你可能需要考虑重构它。请参阅.Null安全运算符的结果取决于上一个运算符的结果。得墨忒尔定律成功了。尽管如此,我还是尽量避免使用一堆lambda来做这个…好吧,thx,好例子=)检查。第二个答案消除了链接,但OMG是一种棘手的实现。然后,正如评论者所说,有LINQ@eocron我想我当时也有过类似的经历,但我现在找不到源头。这是一篇博客文章,不是什么问题,也许它缓存了反射类型以加速执行。在allI考虑过自己做类似的事情后,你会明白为什么这不是那么容易,但试着先问问是否已经做了。我想我可以根据自己的需要调整这个例子。非常感谢=)为什么不升级?VS社区是免费的,基本上与VS Pro相同。您可以使用它以所有运行时为目标。最早受支持的.NET版本是.NET 4.5.2,到2010年还不能成为目标。是的,如果你有一个3.5版本的操作系统,你可以通过操作系统获得支持,但这是一个非常特殊的情况。4.0是绝对不受支持的
public static TOut NullSafe<TIn, TOut>(this TIn obj, Func<TIn, TOut> memberAction)
{
    //Note we should not use obj != null because it can not test value types and also
    //compiler has to lift the type to a nullable type for doing the comparision with null.
    return (EqualityComparer<TIn>.Default.Equals(obj, default(TIn))) 
                         ? memberAction(obj) 
                         : default(TOut);
}
foo.PropagateNulls(x => x.ExtensionMethod().Property.Field.Method());