In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Today, I would like to talk to you about the improvements of Clip6.0 in NullObject, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.
What is a null reference exception
As a programmer who has typed the code, there seems to be no one who hasn't encountered the problem of NullReferenceException. Sometimes when a property or method (delegate) is called inside a method, we control how these properties behave "externally" (except for the use of the ref keyword in some cases). So we have to judge whether the property and delegate method is Null inside the method to avoid the null reference exception caused by possible and misuse, so that when we know that if the object is Null, we will implement the behavior that conforms to our "expectation".
Resolve null reference exception-Check Any Where
It's simple. I just need to check to see if it's Null where I need it. Yes, it's very simple and semantically clear, but when you double-check an object entity 100 million times, you'll have 10000 code snippets in your code:
Public void Check () {if (Person.AlivePerson ()! = null) {Person.AlivePerson (). KeepAlive = true;}}
Can you tolerate such behavior?
If (OK)
Continue
Else
Close
Apply NullObject design pattern
NullObjectPattern comes from forth by Gamma (Design pattern Group of 4). The core content is to provide a null proxy for a given object, and the null proxy provides a method implementation that does nothing.
Next let's take a look at the C# implementation on Wikipedia:
/ / compile as Console Application, requires C # 3.0 or higher using System; using System.Linq; namespace MyExtensionWithExample {public static class StringExtensions {public static int SafeGetLength (this string valueOrNull) {return (valueOrNull?? String.Empty) .length;} public static class Program {/ / define some strings static readonly string [] strings = new [] {"Mr X.", "Katrien Duck", null, "Q"}; / / write the total length of all the strings in the array public static void Main (string [] args) {var query = from text in strings select text.SafeGetLength () / / no need to do any checks here Console.WriteLine (query.Sum ()); / / The output will be: 18}
In the C # language, we use static extension methods to unify the checking method inside the method instead of writing everywhere. In the above example, a SafeGetLength extension method is implemented on the String class, which will provide a method for all String types, so we take another step forward in "code cleanliness".
Let's look at a more common example-from StackOverFlow
Public static class EventExtensions {public static void Raise (this EventHandler evnt, object sender, T args) where T: EventArgs {if (evnt! = null) {evnt (sender, args);}
* to mention a detail, none of the above code has achieved "thread safety". There has been a more exciting discussion on thread safety in Daniel Eric Lippert's article. Please click here.
The improved code adds a temporary variable inside the method as a copy of the method to achieve thread safety. If you have any questions, please refer to my chapter on the performance of the internal variables of the method on the stack in my "C# stack vs stack".
Public class SomeClass {public event EventHandler MyEvent; private void DoSomething () {var tmp = MyEvent; tmp.Raise (this, EventArgs.Empty);}}
A more "trendy" way-Craft 6.0 Grammar
Mark Michaelis from MSDN Magazine (author of "the essence of C #") introduces us to the possible new improvements in the language brought about by Cure 6.0, including improvements to the "Null conditional operator".
More references for Category 6.0:
Part One: https://msdn.microsoft.com/zh-cn/magazine/dn683793.aspx
Part Two: https://msdn.microsoft.com/zh-cn/magazine/dn802602.aspx
Even newcomers to .NET developers may be very familiar with NullReferenceException. One exception is that a Bug is almost always pointed out because the developer does not do adequate null checking before invoking members of the (null) object. Look at the following example:
Public static string Truncate (string value, int length) {string result = value; if (value! = null) / / Skip empty string check for elucidation {result = value.Substring (0, Math.Min (value.Length, length));} return result;}
If there is no null check, this method throws a NullReferenceException. Although this is simple, the process of checking whether the string parameter is null is a bit cumbersome. In general, given the frequency of comparison, this tedious approach may not be necessary. C # 6.0 includes a new null conditional operator to help you write these checks more easily:
Public static string Truncate (string value, int length) {return value?.Substring (0, Math.Min (value.Length, length));} [TestMethod] public void Truncate_WithNull_ReturnsNull () {Assert.AreEqual (null, Truncate (null, 42));}
According to the Truncate_WithNull_ReturnsNull method, if the value of the object is actually null, the null conditional operator returns null. This raises the question of what happens when the null conditional operator appears in the call chain. As shown in the following example:
Public static string AdjustWidth (string value, int length) {return value?.Substring (0, Math.Min (value.Length, length)) .PadRight (length);} [TestMethod] public void AdjustWidth_GivenInigoMontoya42_ReturnsInigoMontoyaExtended () {Assert.AreEqual (42, AdjustWidth ("InigoMontoya", 42) .length);}
Although Substring is called through the null conditional operator, and null value?.Substring seems to return null, the language behaves the way you want. This simplifies the process of calling PadRight and returns null immediately, avoiding programming errors that can lead to NullReferenceException. This concept is called "null propagation".
The Null conditional operator does null checking based on specific conditions, and then invokes the target method and all other methods in the chain. This may produce a surprising result, for example, in the text?.Length.GetType statement.
If the null conditional operator returns null when the call target is null, what data type will it end up with when the call returns a member of the value type (the assumed value type cannot be null)? For example, the data type returned from value?.Length cannot be just int. The answer, of course, is: can it be the type of null (int? ). In fact, trying to assign the result only to int will result in a compilation error:
Int length = text?.Length; / / Compile Error: Cannot implicitly convert type 'int?' To 'int'
Null conditions have two grammatical forms. First, the question mark is preceded by the dot operator. Second, use the question mark in conjunction with the index operator. For example, given a collection (instead of explicitly null checking before indexing to the collection), you can use the null conditional operator to do this:
Public static IEnumerable GetValueTypeItems (IList collection, params int [] indexes) where T: struct {foreach (int index in indexes) {T? Item = collection? [index]; if (item! = null) yield return (T) item;}}
This example uses the operator? [...] Causes the collection to be indexed only if it is not null Through this form of null conditional operator, T? The item = collection? [index] statement behaves like:
T? Item = (collection! = null)? Collection [index]: null.
Note that the null conditional operator only retrieves items and does not assign them. What does this mean if a null set is given?
Please pay attention to the use of reference types? […] The implicit ambiguity of the time. Since the reference type can be null, it comes from? [...] as to whether the collection is null, or whether the element itself is actually null. The null result of the operator is ambiguous.
A very useful application of the Null conditional operator addresses a feature of C # that has existed since C # 1.0, which is to check for null before invoking a delegate. Let's take a look at the C# 2.0 code shown in the figure.
Figure 1 checks whether it is Null before invoking the delegate
Class Theremostat {event EventHandler OnTemperatureChanged; private int _ Temperature; public int Temperature {get {return _ Temperature;} set {/ / If there are any subscribers, then / / notify them of changes in temperature EventHandler localOnChanged = OnTemperatureChanged; if (localOnChanged! = null) {_ Temperature = value; / / Call subscribers localOnChanged (this, value) }
By using the null conditional operator, the entire set implementation can be simplified as follows:
OnTemperatureChanged?.Invoke (this, value)
Now you only need to call Invoke that prefixes the null conditional operator, eliminating the need to assign delegate instances to local variables for thread safety, and even explicitly check whether the value is null before invoking the delegate.
C # developers are curious to know if this has been improved in the four versions of *. The answer is that improvements have finally been made. This feature alone can change the way delegates are called.
Another common pattern in the popularity of null conditional operators is used in conjunction with the coalesce operator. Instead of checking linesOfCode for null before calling Length, you can write a project counting algorithm, as shown below:
List linesOfCode = ParseSourceCodeFile ("Program.cs"); return linesOfCode?.Count? 0
In this case, any empty collection (with no items) and the null collection are standardized to return the same number. In summary, the null conditional operator implements the following functions:
1. Returns null if the Operand is null
two。 If the Operand is null, simplify other calls in the call chain
3. If the target member returns a value type, it returns a type that can be null (System.Nullable).
4. Support for delegate calls in a thread-safe manner
5. Can be used as a member operator (?) And index operator (? [...])
After reading the above, do you have any further understanding of the improvements in NullObject Category 6.0? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.