【问题标题】:I would like to add a string extension method. But where should I add that in my Xamarin Forms application so it's available everywhere?我想添加一个字符串扩展方法。但是我应该在我的 Xamarin Forms 应用程序中的哪个位置添加它,以便它随处可用?
【发布时间】:2026-01-20 08:50:01
【问题描述】:

这是我要添加的方法:

private string S(int i){
  return i == 1 ? "": "s";
}

我想要它,这样我就可以在应用程序的任何部分使用它。但是我应该在哪里添加它,我怎样才能让它在任何地方都可以访问?

【问题讨论】:

  • 看看这个thread
  • 必须是publicstatic

标签: c# xamarin.forms


【解决方案1】:

事实上,这将是一个int 扩展方法。必须是static;此外,为了让它在任何地方都可以访问,它需要是public。扩展方法需要在static class 中定义,并且它们应该在第一个参数之前包含关键字this,这将指示要扩展的类型。所以最终的方法是:

namespace YourNameSpace
{
    public static class Int32Extensions
    {
        public static string S(this int i)
        {
            return i == 1 ? "" : "s";
        }
    }
}

要在其他地方使用它,您需要使用主题代码文件中的命名空间

using YourNameSpace;

简单地称呼它

int i = 3;
string str = i.S(); //equals "s"

【讨论】:

    【解决方案2】:

    您展示的方法不是扩展方法。扩展方法(例如)是这样的:

    public static class MyStringExtensions
    {
        public static string S(this string text, int i)
        {
            return i == 1 ? "" : text;
        }
    }
    

    方法必须是静态的,必须在静态类中,并且第一个参数在声明前必须有关键字this

    将类放入命名空间的基础中,这样您就可以自动从任何地方访问它,而无需使用using 指定命名空间。

    【讨论】:

      最近更新 更多