Janus007
Janus007

Reputation: 366

Invoke method in Func when passed as parameter

I was creating a Func as parameter input to another method, but how do I invoke that?

The following code describes my work:

I call Foo with:

Foo(x => x.SlidingExpiration(TimeSpan.FromSeconds(50)));

My method Foo:

public void Foo(Func<CacheExpiration, TimeSpan> cacheExpiration)
{
....
inside here I want to call RefreshCache, but how?.. cacheExpiration.??

}

The CacheExpiration :)

public class CacheExpiration
        {
            TimeSpan timeSpan;
            bool sliding;

            public TimeSpan SlidingExpiration(TimeSpan ts)
            {
                this.timeSpan = ts;
                this.sliding = true;
                return ts;
            }
            public TimeSpan AbsoluteExpiration(TimeSpan ts)
            {
                this.timeSpan = ts;
                return ts;
            }

            public bool RefreshCache(MetaObject mo)
            {
                //some logic....
                return true;
            }

        }

Upvotes: 0

Views: 123

Answers (2)

Daniel Ballinger
Daniel Ballinger

Reputation: 13537

If I'm reading this correctly then the Func cacheExpiration takes a CacheExpiration instance and returns a TimeSpan. So I could see the body of Foo being:

TimeSpan ts = cacheExpiration.SlidingExpiration(TimeSpan.FromSeconds(50));
//or
TimeSpan ts2 = cacheExpiration.AbsoluteExpiration(TimeSpan.FromSeconds(50));

This doesn't line up with the lamda in your example so I'm guessing from that you really want cacheExpiration to be a Func that takes a Timespan and returns a TimeSpan. But this wouldn't work for the RefreshCache method as it takes a MetaObject and returns a boolean.

Upvotes: 0

leppie
leppie

Reputation: 117230

var ts = cacheExpiration(yourCacheExpiration);

Upvotes: 1

Related Questions