帮助C#拉姆达EX pression拉姆、EX、pression

由网友(好听又个性的抖音昵称 最吸引人的抖音昵称)分享简介:我拉着所有的先进功能,共同为这一个,但还没有与仿制药或lambda EX pressions非常多:I'm pulling all of the advanced features together for this one, but haven't worked with generics or lambda ex...

我拉着所有的先进功能,共同为这一个,但还没有与仿制药或lambda EX pressions非常多:

I'm pulling all of the advanced features together for this one, but haven't worked with generics or lambda expressions very much:

下面就是该方法的用法示例,我想创建:

Here's example usage of the method I want to create:

MyClass mc = null;
int x = mc.TryGetOrDefault(z => z.This.That.TheOther); // z is a reference to mc
// the code has not failed at this point and the value of x is 0 (int's default)
// had mc and all of the properties expressed in the lambda expression been initialized
// x would be equal to mc.This.That.TheOther's value

下面是据我已经得到了,但我不知道该怎么做这个EX pression对象。

Here's as far as I've gotten, but I'm not sure what to do with this expression object.

[的 1

推荐答案

这是诸如此类的事情,你是后?

Is this the sort of thing you're after?

public static TResult TryGetOrDefault<TSource, TResult>(this TSource obj, Func<TSource, TResult> expression)
{
    if (obj == null)
        return default(TResult);

    try
    {
        return expression(obj);
    }
    catch(NullReferenceException)
    {
        return default(TResult);
    }
}
阅读全文

相关推荐

最新文章