c#是否可以为字符串关键字创建扩展方法
c# is it possible to create extension method for string keyword
我创建了一个扩展方法来像这样从 System.Guid
生成字符串。
public static class Fnk
{
public static string Guid(bool dash = true)
{
return dash ? System.Guid.NewGuid().ToString() : System.Guid.NewGuid().ToString("N");
}
}
我像 Fnk.Guid()
一样使用它。我想知道,是否可以像 string.Guid()
这样称呼它?如果是,如何?
Is it possible to call it like string.Guid()
没有。扩展方法允许调用静态方法,就好像它们是实例方法一样。您正在尝试编写一个静态方法并允许它被调用 ,就好像它是一个不相关类型的静态方法一样。
不支持 - 至少从 C# 8 开始不支持。
针对string
编写真正的扩展方法是完全可行的。例如:
public static class PointlessExtensions
{
public static HasEvenLength(this string text) => (text.Length & 1) == 0;
}
称为:
bool result1 = "odd".HasEvenLength(); // False
bool result2 = "even".HasEvenLength(); // True
我创建了一个扩展方法来像这样从 System.Guid
生成字符串。
public static class Fnk
{
public static string Guid(bool dash = true)
{
return dash ? System.Guid.NewGuid().ToString() : System.Guid.NewGuid().ToString("N");
}
}
我像 Fnk.Guid()
一样使用它。我想知道,是否可以像 string.Guid()
这样称呼它?如果是,如何?
Is it possible to call it like
string.Guid()
没有。扩展方法允许调用静态方法,就好像它们是实例方法一样。您正在尝试编写一个静态方法并允许它被调用 ,就好像它是一个不相关类型的静态方法一样。
不支持 - 至少从 C# 8 开始不支持。
针对string
编写真正的扩展方法是完全可行的。例如:
public static class PointlessExtensions
{
public static HasEvenLength(this string text) => (text.Length & 1) == 0;
}
称为:
bool result1 = "odd".HasEvenLength(); // False
bool result2 = "even".HasEvenLength(); // True