开发者

How to capture static or non static property by using lambda expression?

开发者 https://www.devze.com 2022-12-14 08:13 出处:网络
There are a lot of benefits for using lambda expression to capture property or method of some class like the following code.

There are a lot of benefits for using lambda expression to capture property or method of some class like the following code.

void CaptureProperty<T, TProperty> (Func<T, TProperty> exp)
{
   // some logic to keep exp variable
}

// So you can use below code 开发者_如何学Goto call above method.
CaptureProperty<string, int>(x => x.Length);

However, the above code does not support static property. So, how to create method that support both static property and non-static property?

Thanks,


Well, you can capture a static property that way:

CaptureProperty<string, Encoding>(x => Encoding.UTF8);

You then need to provide a "dummy" value at execution time though...

An alternative would be to provide another overload with only a single type argument:

void CaptureProperty<T>(Func<T> func)
{
    // Whatever
}

Use is like this:

CaptureProperty<Encoding>(() => Encoding.UTF8);

Is that what you're after?

If you wanted to unify the two internally, you could have a "dummy" private nested type within the same type as CaptureProperty and implement the static version like this:

void CaptureProperty<T>(Func<T> func)
{
    CaptureProperty<DummyType, T>(x => func());
}

Then you could detect that the "source" type is DummyType when you need to call the function later. This may or may not be a useful idea depending on what else you're doing :)

0

精彩评论

暂无评论...
验证码 换一张
取 消