gpt4 book ai didi

c# - 向字符串类添加扩展方法 - C#

转载 作者:可可西里 更新时间:2023-11-01 07:49:12 26 4
gpt4 key购买 nike

不确定我在这里做错了什么。无法识别扩展方法。

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;
}
}
}

最佳答案

您正在尝试在 type 字符串上调用它。您需要在字符串实例 上调用它,例如

"{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");

扩展方法的要点在于它们看起来像扩展类型上的实例 方法。您不能在扩展类型上创建看似静态方法的扩展方法。

关于c# - 向字符串类添加扩展方法 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1676191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com