1. Duck Typing ("If it walks like a duck and quacks like a duck, it must be a duck.") [Refer to here]

Duck typing allows an object to be passed in to a method that expects a certain type even if it doesn’t inherit from that type. All it has to do is support the methods and properties of the expected type in use by the method.

my object does not have to support all methods and properties of ​​duck​​ to be passed into a method that expects a ​​duck​. Same goes for a method that expects a ​​rabbit. ​​It only needs to support the methods and properties of the expected type that are actually called by the method.

Example:



  1. public interface IReadOnlyRestricable   
  2.   {   
  3.   bool ReadOnly { get; set; }   
  4.   } 

然后我们要遍历所有的控件,找出有ReadOnly属性的控件并把此属性设为true(译者注:这些控件本身没有实现 IReadOnlyRestricable),在ducktyping下我们可以把控件通过类型转换为IReadOnlyRestricable,就像下 面代码一样,这样我们就不需要通过反射去定位ReadOnly属性了:




  1. foreach (Control c in f.Controls)
  2. {
  3. //希望有隐式转换
  4. IReadOnlyRestrictable if interface contract is in class we are checking against
  5. IReadOnlyRestricable editable = c as IReadOnlyRestricable;
  6. if (editable != null)
  7. editable.ReadOnly = true;
  8. }


C# has used duck typing for a long time

Interestingly enough, certain features of C# already use duck typing. For example, to allow an object to be enumerated via the C# ​​foreach​​​ operator, the object only needs to implement a set of methods as Krzystof Cwalina​ of Microsoft points out in this post...


Provide a public method ​​GetEnumerator​​​ that takes no parameters and returns a type that has two members: a) a method ​​MoveNext​​​ that takes no parameters and return a Boolean, and b) a property ​​Current​​​ with a getter that returns an ​​Object​​.


You don’t have to implement an interface to make your object enumerable via the ​​foreach​​ operator.


From Bruce eckel:

What I’m trying to get to is that in my experience there’s a balance between the value of strong static typing and the resulting impact that it makes on your productivity. The argument that "strong static is obviously better" is generally made by folks who haven’t had the experience of being dramatically more productive in an alternative language. When you have this experience, you see that the overhead of strong static typing isn’t always beneficial, because sometimes it slows you down enough that it ends up having a big impact on productivity.


2. Safe Null checking


  1. //这将返回null,如果客户是空或者如果命令是空