C# Laajennetut luokat

24 July 2008 by

Tuli luettua C# kielioppia. Mukavana ominaisuutena huomasin että nykyään pystytään (versiosta 3.0 lähtien) laajentamaan valmiita kirjastoluokkia. Tämä avaa mukavia mahdollisuuksia poistaa itseään häiritseviä piirteitä.

Laajennuksen tekeminen onnistuu lisäämällä this sana metodin parametrin määrittelyyn. Alla esimerkki string luokan laajennuksesta.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Text.RegularExpressions;
 
namespace StringExtensions
{
    public static class StringExtensions
    {
        /// <summary>
        /// Remove any non-numeric characters and then return the resultant string.
        /// Useful for parsing phone numbers.
        /// </summary>
        /// <param name="s">The text that is to be evaluated.</param>
        /// <returns>New string</returns>                 
        public static string RemoveNonNumeric(this string s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
                if (Char.IsNumber(s[i]))
                    sb.Append(s[i]);
            return sb.ToString();
        }
 
        /// <summary>
        /// Returns the substring of the first argument string that follows the first occurrence 
        /// of the second argument string in the first argument string, or the empty 
        /// string if the first argument string does not contain the second argument string.
        /// </summary>
        /// <param name="source">The text that is to be evaluated.</param>
        /// <param name="value">String to search.</param>
        /// <returns>New string</returns>
        public static string SubstringAfter(this string source, string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return source;
            }
            CompareInfo compareInfo = CultureInfo.InvariantCulture.CompareInfo;
            int index = compareInfo.IndexOf(source, value, CompareOptions.Ordinal);
            if (index < 0)
            {
                //No such substring
                return string.Empty;
            }
            return source.Substring(index + value.Length);
        }
 
        /// <summary>
        /// Returns the substring of the first argument string that precedes the first occurrence of 
        /// the second argument string in the first argument string, or the empty string if 
        /// the first argument string does not contain the second argument string.
        /// </summary>
        /// <param name="source">The text that is to be evaluated.</param>
        /// <param name="value">String to search.</param>
        /// <returns>New string</returns>
        public static string SubstringBefore(this string source, string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return value;
            }
            CompareInfo compareInfo = CultureInfo.InvariantCulture.CompareInfo;
            int index = compareInfo.IndexOf(source, value, CompareOptions.Ordinal);
            if (index < 0)
            {
                //No such substring
                return string.Empty;
            }
            return source.Substring(0, index);
        }
 
        /// <summary>
        /// Truncate string using dots...
        /// Useful for displaying long filename paths.
        /// </summary>
        /// <param name="s">String to be truncated.</param>
        /// <param name="maxLength">Maximum string size</param>
        /// <returns>New string</returns>
        public static string Truncate(this string s, int maxLength)
        {
            if (string.IsNullOrEmpty(s) || maxLength <= 0)
                return string.Empty;
            else if (s.Length > maxLength)
                return s.Substring(0, maxLength) + "...";
            else
                return s;
        }
 
        /// <summary>
        /// Reverse string.
        /// </summary>
        /// <param name="s">String to be reversed.</param>
        /// <returns>Reversed string.</returns>
        public static string Reverse(this string s)
        {
            char[] c = s.ToCharArray();
            Array.Reverse(c);
            return new string(c);
        }
 
        /// <summary>
        /// Test if string contains only numbers.        
        /// </summary>
        /// <param name="text">The text that is to be evaluated.</param>
        /// <returns>True if text included only letters.</returns>
        public static bool IsAlpha(this string text)  
        {            
            foreach (char c in text.ToLower())  
            {  
                if (!char.IsLetter(c))
                    return false;  
            }  
            return true;  
        }
 
        /// <summary>
        /// Check is string is valid email address.
        /// </summary>
        /// <param name="email">Email to be checked.</param>
        /// <returns>True if email address was ok.</returns>        
        public static bool IsValidEmailAddress(this string email)
         {             
             const string REGEX_VALID_EMAIL =
                 @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|" +
                 @"(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
             bool valid = Regex.IsMatch(email, REGEX_VALID_EMAIL);
             return valid;
         }
 
        /// <summary>
        /// Convert string to integer.
        /// </summary>
        /// <param name="s">String to be processed.</param>
        /// <returns>Integer</returns>
        public static int ToInteger(this string s)
        {
            int integerValue = 0;
            int.TryParse(s, out integerValue);
            return integerValue;
        }
 
        /// <summary>
        /// Compare two strings, ignore case.
        /// </summary>
        /// <param name="s1">String 1</param>
        /// <param name="s2">String 2</param>
        /// <returns>If equal return true.</returns>
        public static bool Comparei(this string s1, string s2)
        {
            CompareInfo Compare = CultureInfo.InvariantCulture.CompareInfo;
            int i = Compare.IndexOf(s1, s2, CompareOptions.IgnoreCase);
            if (i != 0 )
                return true;
            else
                return false;
        }
    }
}

Comment here

XHTML: Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">