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:
- public interface IReadOnlyRestricable
- {
- bool ReadOnly { get; set; }
- }
- foreach (Control c in f.Controls)
- {
- //希望有隐式转换
- IReadOnlyRestrictable if interface contract is in class we are checking against
- IReadOnlyRestricable editable = c as IReadOnlyRestricable;
- if (editable != null)
- editable.ReadOnly = true;
- }
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 methodMoveNext
that takes no parameters and return a Boolean, and b) a propertyCurrent
with a getter that returns anObject
.
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
- //这将返回null,如果客户是空或者如果命令是空
- int? orderNumber = Customer?.Order?.OrderNumber;