简体   繁体   中英

Does C# have a equivalent to Objective-c's category?

我正在寻找与C#语言的Objective-c类别相当的东西。

You can't add methods to a class, however you can use extension methods to achieve similar effects.

make a static class, with a static method. The static methods first argument is marked with "this" and the method is decorated to the classes with the type of the argument.

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

This method will then be available on all instances of the type String. However you still have to have the extension class available through your usings.

The example is taken from Microsoft's own documention available here: http://msdn.microsoft.com/en-us/library/bb383977.aspx

The closest thing to Objective-C Categories in C# is Extension Methods .

Note that C# is a statically typed language and doesn't use dynamic dispatching like Objective-C does. That means that method resolution is performed at compile time and not at runtime, like you are used to in Objective-C.

Related resources:

Don't categories allow you to add methods to existing classes without subclassing them? If so then extension methods would be the C# equivalent. They won't replace existing methods though and are subject to a few constraints.

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