string user function
how can i add a custom function to a string type
example:
string test = "hello";
test.userFn("world");
public string userFn(s开发者_如何学JAVAtrng str) {
return " " + str;
}
http://msdn.microsoft.com/en-us/library/bb383977.aspx
namespace ExtensionMethods
{
public static class MyExtensions
{
public static string userFn(this string str)
{
return " " + str;
}
}
}
You can't add a custom function, but you can use extension methods to approximate this:
public static class StringExtensions {
public static string userFn(this string str) {
return " " + str;
}
}
Depends on what framework you are using, if you are using 3.5, then yes you can add extensions to the String class, thereby extending it to include your methods/properties. Have a look here for an example of extending the String class.
Hope this helps, Best regards, Tom.
You should check .net 3.0 extension methods Here
Take a look at Extension methods.
Microsoft example:
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
精彩评论