Does C# have a equivalent to Objective-c's category?
I'm looking for a equi开发者_JS百科valent to the Objective-c's Category for C# language.
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:
- The Objective-C Programming Language: Categories and Extensions
- Extension Methods (C# Programming Guide)
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.
精彩评论