Adding an extension method to the string class - C#
Not sure what I'm doing wrong here. The extension method is not recognized.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using StringExtensions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
开发者_C百科 RunTests();
}
static void RunTests()
{
try
{
///SafeFormat
SafeFormat("Hi There");
SafeFormat("test {0}", "value");
SafeFormat("test missing second value {0} - {1}", "test1");
SafeFormat("{0}");
//regular format
RegularFormat("Hi There");
RegularFormat("test {0}", "value");
RegularFormat("test missing second value {0} - {1}", "test1");
RegularFormat("{0}");
///Fails to recognize the extension method here
string.SafeFormat("Hello");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
private static void RegularFormat(string fmt, params object[] args)
{
Console.WriteLine(String.Format(fmt, args));
}
private static void SafeFormat(string fmt, params object[] args)
{
string errorString = fmt;
try
{
errorString = String.Format(fmt, args);
}
catch (System.FormatException) { } //logging string arguments were not correct
Console.WriteLine(errorString);
}
}
}
namespace StringExtensions
{
public static class StringExtensionsClass
{
public static string SafeFormat(this string s, string fmt, params object[] args)
{
string formattedString = fmt;
try
{
formattedString = String.Format(fmt, args);
}
catch (System.FormatException) { } //logging string arguments were not correct
return formattedString;
}
}
}
You're trying to call it on the type string. You need to call it on a string instance, e.g.
"{0}".SafeFormat("Hello");
Admittedly that won't do what you want it to, because the SafeFormat method is actually completely ignoring the first parameter (s
) anyway. It should look like this:
public static string SafeFormat(this string fmt, params object[] args)
{
string formattedString = fmt;
try
{
formattedString = String.Format(fmt, args);
}
catch (FormatException) {} //logging string arguments were not correct
return formattedString;
}
Then you can call:
"{0} {1}".SafeFormat("Hi", "there");
The point of extension methods is that they look like instance methods on the extended type. You can't create extension methods which appear to be static methods on the extended type.
You're defining an instance extension method, and then trying to use it as a static method. (C# is not capable of defining a static extension method, though F# is for that matter.)
Instead of:
result = string.SafeFormat("Hello");
you want something like:
result = "Hello".SafeFormat();
i.e. You're operating on the string instance ("Hello" in this case).
Extension methods appear on instances of a type, not the type itself (e.g. static members).
try
"Hello".SafeFormat("{0} {1}", "two", "words")
精彩评论