'func'에 해당되는 글 1건

  1. 2009.07.17 Action<T> and Func<TResult> delegates
모아온 글(번역)2009.07.17 14:46
원문 보기 : http://marekblotny.blogspot.com/2009/04/action-and-func-delegates.html
 
이 포스트에서 최근 ASP.NET 3.5에서 추가된 내가 좋아하는 두 가지 타입의 델리게이트를 소개할까 한다.
(System Namespace):

Action<T> - "매개 변수가 하나이고 값을 반환하지 않는 메서드를 캡슐화합니다". 파라미터는 2, 3, 4개까지 가질 수 있는
추가버전이 있습니다. 아래와 같이 사용할 수 있습니다.:

더보기


To updated page in EPiServer it's required to create writable clone first, then we can apply our changes and finally instance of PageData has to be saved. This is a procedure which you can probably find in many places in your projects. With delegates you can easily "close" standard steps into a single method and pass changeable part as a parameter, like this:

더보기


I think it should be pretty obvious that the above piece of code changes MetaAuthor and MainBody properties on CurrentPage. For me, main benefit of this approach is increased readability, hence the code is easier to maintain. Note that there is nothing in this call about creating writable clone, calling save method on DataFactory, those are all important and required steps to get things working properly but in the same time they are irrelevant from businesses logic point of view. You don't need to see those "standard" actions to understand what your class/method is doing.

You can also use delegates which return a value:
Func<TResult> - "매개 변수가 하나이고 TResult 매개 변수에 지정된 형식의 값을 반환하는 메서드를 캡슐화합니다."

이 예제에서, 메서드가 반환하는 기본값 속성 또는 경우 존재하지 않는 설정되어 있지 않다. 만약 속성을 누른 다음 값은 좀 특별한 방법으로 포맷할 수있습니다 설정되어있습니다
In this example, method returns default value if property doesn't exist or is not set. If property is set then its value can be formatted in some special way:

   

더보기


And this is how this method can be used:

더보기


In the above example we are interested in EventDate property, if this property is not set then empty string (default value) will be returned, otherwise DateTime will be formatted appropriately.

Of course, in pre-ASP.NET 3.5 era things like this were also possible but it was required to define your own delegates etc. Now you can use those which are available for you in the framework. Personally I really like lambda expressions and this "way" of crating APIs, it's much more readable for me therefore I encourage you to give it a try! :)
Posted by UXPRO
TAG ,