向字符串类添加扩展方法 - C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1676191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding an extension method to the string class - C#
提问by Chris Ballance
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)
{
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;
}
}
}
采纳答案by Jon Skeet
You're trying to call it on the typestring. 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:
不可否认,这不会做你想要的,因为 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;
}
Then you can call:
然后你可以调用:
"{0} {1}".SafeFormat("Hi", "there");
The point of extension methods is that they look like instancemethods on the extended type. You can't create extension methods which appear to be staticmethods on the extended type.
扩展方法的要点在于它们看起来像扩展类型上的实例方法。您不能在扩展类型上创建看起来是静态方法的扩展方法。
回答by Marek Karbarz
try
尝试
"Hello".SafeFormat("{0} {1}", "two", "words")
回答by Noldorin
You're defining an instanceextension method, and then trying to use it as a staticmethod. (C# is not capable of defining a static extension method, though F# is for that matter.)
您正在定义一个实例扩展方法,然后尝试将其用作静态方法。(C# 不能定义静态扩展方法,但 F# 可以。)
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).
即您正在操作字符串实例(在本例中为“Hello”)。
回答by Rex M
Extension methods appear on instances of a type, not the type itself (e.g. static members).
扩展方法出现在类型的实例上,而不是类型本身(例如静态成员)。