what is the point of allowing invocation of extension methods on null objects? this is making me unnecessarily check for a null object in the extension method. AFAIK,i can't understand this? Please explain.
问题:
回答1:
Extension methods are syntactic sugar of the C# language, they get compiled to normal static method calls in ILCode. A static method doesn't know anything about the parameters at compile time.
回答2:
Simply put, why not?
You can sometimes skip the test if the first method you call within the extension would also throw the correct error.
You're essentially asking for the code to be different so that:
- Uses which are reasonable on a null object, become disallowed.
- Uses which don't need a null check (because it's implicit in something else) get the overhead of the needless check you want to happen automatically.
This seems a lot of an imposition on other uses just to save the one line of:
if(arg == null)throw new ArgumentNullException();
回答3:
Extension methods are just syntactic sugar. In reality they are static methods on another class, so since you can write
IEnumerable<int> foo = null;
Enumerable.Count(foo);
You can also write
IEnumerable<int> foo = null;
foo.Count();
回答4:
Sometimes, allowing the extension method to be called on a null object simplifies your code by allowing you to move the null check into the method instead at the call site. For example, you may have an extension method that returns a List<T>
, but if called on a null object, returns an empty List<T>
.
回答5:
- Extension methods are transformed to static method invocations so the code will still need to check for null arguments as there is no way to avoid the static method to be called normally without the extension method syntactic sugar.
- Adding something like a check followed by a
NullArgumentException
could take execution time and the user may want to assert instead or use something else. - It would make the replacement more complex to explain or do automatically as the simple replacement of the extension method with the corresponding static method call will change the behavior of the code.
- There are legitimate case where you want to allow null arguments (for exemple conversions from an object model to another where a null object of one type is converted to a null object of the second type)
回答6:
Extension methods are just static methods:
List<int> x = null;
x.Count()
Is equivalent to:
List<int> x = null;
System.Linq.EnumerableExtensions.Count(x);
//EnumerableExtensions may not be the class, but you get the idea
回答7:
Another beautiful example that wouldn't be possible otherwise:
public static bool IsNullOrEmpty(this string value)
{
return string.IsNullOrEmpty(value);
}
So you can use
string s = null;
if (s.IsNullOrEmpty()) // no null reference error!
...
Instead of
string s = null;
if (string.IsNullOrEmpty(s))
....