To reduce the loss caused by the abnormal NullReferenceException

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

To reduce the loss caused by the abnormal NullReferenceException

A few days ago, ILoveSleep wrote a blog "let <object reference not set to an instance of > go to hell! "To many bloggers criticized, but in fact I think should not say things on a blog, after all ILoveSleep is sharing his thoughts, there is a problem, to say, to see him on your reply is also very modest, is certainly can accept the opinions of others. Today I say to you I NullReferenceException spray, the people are not afraid to spray.

ILoveSleep not so good patience to explain to you, at the same time, the code is very simple, just paste the code

Class PreventNull<T>

 1 using System;
 2 using System.Threading;
 3 
 4 namespace PreventNullDemo
 5 {
 6     public class PreventNull<T> : Lazy<T> 
 7     {
 8 
 9         /// <summary>
10         /// The initialization of System.LazyExd<T> A new instance of the class. Delayed initialization, the default constructor using target type. 
11         /// </summary>
12         public PreventNull() : base() { }
13 
14         /// <summary>
15         ///  The initialization of System.LazyExd<T> A new instance of the class. Delayed initialization, using the object type's default constructor and the specified initialization mode. 
16         /// </summary>
17         /// <param name="isThreadSafe">True said this example can be used simultaneously by multiple threads; false said the example one can only be used by one thread. </param>
18         public PreventNull(bool isThreadSafe) : base(isThreadSafe) { }
19 
20 
21         /// <summary>
22         /// The initialization of System.LazyExd<T> A new instance of the class. Delayed initialization initialization function, using the specified. 
23         /// </summary>
24         /// <param name="valueFactory">When needed to generate a delay delegate value. </param>
25         public PreventNull(Func<T> valueFactory) : base(valueFactory) { }
26 
27         public PreventNull(LazyThreadSafetyMode mode) : base(mode) { }
28 
29         public PreventNull(Func<T> valueFactory, bool isThreadSafe) : base(valueFactory, isThreadSafe) { }
30 
31         /// <summary>
32         /// The initialization of System.LazyExd<T> A new instance of the class, which uses the specified initialization function and thread safety mode. 
33         /// </summary>
34         /// <param name="valueFactory">When needed to generate a delay delegate value. </param>
35         /// <param name="mode">Thread safety mode. </param>
36         public PreventNull(Func<T> valueFactory, LazyThreadSafetyMode mode) : base(valueFactory, mode) { }
37 
38         /// <summary>
39         /// 
40         /// </summary>
41         /// <param name="value"></param>
42         /// <returns></returns>
43         public static implicit operator T(PreventNull<T> value)
44         {
45             return value.Value;
46         }
47 
48         public static explicit operator PreventNull<T>(T value)
49         {
50             return new PreventNull<T>(new Func<T>(() => { return value; }));
51         }
52 
53 
54 
55         new public T Value
56         {
57             get
58             {
59                 if (base.Value == null)
60                 {
61                     if (NullErrorLog != null)
62                         NullErrorLog(this);
63                     return NullDefaltValue();
64                 }
65                 return base.Value;
66             }
67         }
68 
69         /// <summary>
70         /// The value of the log is empty
71         /// </summary>
72         public static Action<PreventNull<T>> NullErrorLog { get; set; }
73 
74         /// <summary>
75         /// But the value of null, to use the value of this property replaces null value
76         /// </summary>
77         public static Func<T> NullDefaltValue { get; set; }
78     }
79 }

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PreventNullDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //You can create a static class to manage settings
            //PreventNull<Person>.NullErrorLog = new Action<PreventNull<Person>>((p) => { Console.WriteLine("A null object.!"); });
            //PreventNull<Person>.NullDefaltValue = new Func<Person>(() => { return new Person() { Name = "null"}; });

            //The class management settings
            PreventNullConfig.Config();

            //Use case
            Person p1 = new PreventNull<Person>(new Func<Person>(() => { return new Person() { Name = "xxx" }; }));
            Person p2 = new PreventNull<Person>(new Func<Person>(() => { return null; }));
            //Person p3 = new Person() { Name = "xxx" } as PreventNull<Person>;
            Person p4 = (PreventNull<Person>)new Person() { Name = "xxx" };
            Person p5 = new PreventNull<Person>(new Func<Person>(() => { return null; }));
            Person p6 = (PreventNull<Person>)Person.CreateNull();
            Console.WriteLine(p1.Name);
            Console.WriteLine(p2.Name);
            Console.WriteLine(p4.Name);
            Console.WriteLine(p5.Name);
            Console.WriteLine(p6.Name);
            Console.Read();
        }

        
    }


    static class PreventNullConfig
    {
        public static void Config()
        {
            //You can create a static class to manage settings
            PreventNull<Person>.NullErrorLog = new Action<PreventNull<Person>>((p) => { Console.WriteLine("A null object.!"); });
            PreventNull<Person>.NullDefaltValue = new Func<Person>(() => { return new Person() { Name = "null" }; });
        }
    }


    class Person
    {
        public string Name { get; set; }

        public static Person CreateNull()
        {
            return null;
        }
    }
}




The operation results



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Polly at November 15, 2013 - 7:18 PM