简体   繁体   中英

C# creating extension method

Hallo I would like to create an extension method for Char class that works as Char.IsDigit() method (but that will of course recognize a differnt type of characters). I wrote this:

namespace CharExtensions
{
    public static class CompilerCharExtension
    {
        public static Boolean IsAddOp(this Char c)
        {
            return c.Equals('+') || c.Equals('-');
        }
    }
}

that works fine but that it's not exactly what I meant. This extension should be used this way:

using CharExtensions;
char x:
...
if(x.IsAddOp())
    Console.WriteLine("Add op found");

While I would something like this:

using CharExtensions;
char x;
...
if(Char.IsAddOp(x))
    Console.WriteLine("Add op found");

Thanks to everyone who could help me.

You cannot do that, as extension methods will always require an instance of the object. See here

Extension methods are defined as static methods but are called by using instance method syntax.

Your question mention to fire a static method of a class. You actually want to define a static method for Char class, not add a extension to char instance. to define a static method you must access the original class something like

class SomeClass {
    public int InstanceMethod() { return 1; }
    public static int StaticMethod() { return 42; }
}

Now you can use StaticMethod as:

SomeClass.StaticMethod();  

Then you must access to Microsoft .net framework code to add IsAddOp(x) method to Char class. Actually your way to define a extension with that one you say in question is wrong.. you dont try to define Extension method..you try to define Static method.

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