c#是否可以为字符串关键字[duplicate]创建扩展方法

问题描述 投票:0回答:1

我创建了这样的扩展方法,用于从System.Guid生成字符串。

public static class Fnk
{

    public static string Guid(bool teqel = true)
    {
        var guid = System.Guid.NewGuid().ToString();
        return teqel ? guid : guid.Replace("-", "");
    }
}

我正在像Fnk.Guid()一样使用它。我想知道,是否可以像string.Guid()那样称呼它?如果是,如何?

c# extension-methods
1个回答
2
投票

是否可以像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
© www.soinside.com 2019 - 2024. All rights reserved.