简体   繁体   中英

Create methods like .ToString()

I want to create my own methods like .ToString() which I want to use on my own project.

For example ToDecimalOrZero() which I want to convert the data into decimal, or if the data is empty convert it to zero.

I know I shouldn't ask for codes here, but I don't have the slightest idea how I can do that.

Can anyone help me out? Or at least refer me somewhere... I'm kinda lost. Thanks :)

Here an example of how to write your own extension methods

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, 
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }   
}

from MSDN

Note that extension methods have to be static , as well as the class that contains extension methods

Use extension methods:

namespace ExtensionMethods
{
    public static class StringExtensions
    {
        public static decimal ToDecimalOrZero(this String str)
        {
            decimal dec = 0;
            Decimal.TryParse(str, out dec);
            return dec;
        }
    }   
}

using ExtensionMethods;
//...
decimal dec = "154".ToDecimalOrZero(); //dec == 154
decimal dec = "foobar".ToDecimalOrZero(); //dec == 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM