Добавление метода расширения в класс строк - С#
Не уверен, что я здесь делаю неправильно. Метод расширения не распознается.
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)
{
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;
}
}
}
Ответы
Ответ 1
Вы пытаетесь вызвать его в строке типа. Вам нужно вызвать его в экземпляре строки, например.
"{0}".SafeFormat("Hello");
По общему признанию, это не будет делать то, что вы хотите, потому что метод SafeFormat фактически полностью игнорирует первый параметр (s
). Он должен выглядеть следующим образом:
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;
}
Затем вы можете позвонить:
"{0} {1}".SafeFormat("Hi", "there");
Точкой методов расширения является то, что они выглядят как методы экземпляра расширенного типа. Вы не можете создавать методы расширения, которые, как представляется, являются статическими методами расширенного типа.
Ответ 2
Вы определяете метод расширения экземпляра, а затем пытаетесь использовать его как статический метод. (С# не может определить статический метод расширения, хотя F # имеет значение.)
Вместо:
result = string.SafeFormat("Hello");
вам нужно что-то вроде:
result = "Hello".SafeFormat();
то есть. Вы работаете в экземпляре строки ( "Hello" в этом случае).
Ответ 3
Методы расширения отображаются в экземплярах типа, а не в самом типе (например, статические элементы).
Ответ 4
попробовать
"Hello".SafeFormat("{0} {1}", "two", "words")