- Inside a class, when we write
public class PhotoFilter { public deletegate void PhotoFilterHandler(Photo phpto); }
we are defining a signature of functions that is described by "PhotoFilterHandler", namely, any function that takes an Photo type input into void output can be called of type PhotoFilterHandler. This is analagous to defining an interface of the method "PhotoFilterHandler" in side any object of type "PhotoFilter" in Javascript:
public interface PhotoFilter {PhotoFilterHandler: (photo: Photo) => void;}
The type can be directly referred byPhotoFilter.PhotoFilterHandler
(<~~ this is a type, not a method/property). - The above is called a custom delegate, by writing
using System
on the top we can write equivalentlyAction<T1>
for any functions that take T1 type element into void, or writeFunc<T1> or Func<T1, void>
Note that we can also writeFunc<T1, T2, T3, ..., T16, void>
for more parameters. - Interface in C# is almost the same as that in Javascript, except that in Javascript we use interface to put constraint on OBJECT, while in C# we put constraint on CLASS.
interface IPen { string Color { get; set; } bool Open(); bool Close(); void Write(string text); }
- From experience when implementing an interface, we will be just required to implement the logic of methods, while properties are not required when we define the class. It wouldn't throw a compilation error saying that some properties in the interface is not yet defined.
- When using linq.Single or .FindAll method in a list, we usually see Predicate:
Roughly speaking:
Predicate<T> = Func<T, bool>
- All delegates in C# are multicast delegates, i.e., by call them may cast multiple functions at the same time. Two functions of the same delegate can be joined together using + operator, by joining we mean that they will be executed one after another.
Saturday, August 24, 2019
Interface, Delegate and Predicate
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment