Why do we need C# delegates

前端 未结 8 677
遥遥无期
遥遥无期 2020-12-22 19:47

I never seem to understand why we need delegates? I know they are immutable reference types that hold reference of a method but why can\'t we just call the method directly,

8条回答
  •  醉话见心
    2020-12-22 20:32

    You asked for an example of why you would pass a function as a parameter, I have a perfect one and thought it might help you understand, it is pretty academic but shows a use. Say you have a ListResults() method and getFromCache() method. Rather then have lots of checks if the cache is null etc. you can just pass any method to getCache and then only invoke it if the cache is empty inside the getFromCache method:

    _cacher.GetFromCache(delegate { return ListResults(); }, "ListResults");

    public IEnumerable GetFromCache(MethodForCache item, string key, int minutesToCache = 5)
        {
            var cache = _cacheProvider.GetCachedItem(key);
            //you could even have a UseCache bool here for central control
            if (cache == null)
            {
                //you could put timings, logging etc. here instead of all over your code
                cache = item.Invoke();
                _cacheProvider.AddCachedItem(cache, key, minutesToCache);
            }            
    
            return cache;
        }
    

提交回复
热议问题