gpt4 book ai didi

c#无参数扩展方法

转载 作者:太空宇宙 更新时间:2023-11-03 18:31:20 24 4
gpt4 key购买 nike

<分区>

是否可以创建不带参数的扩展方法?我是使用扩展方法的新手,只见过它们使用参数。

来自 RB Whitaker's C# tutorial :

public static class StringExtensions
{
private static Random random = new Random();

public static string ToRandomCase(this string text)
{
string result = "";

for (int index = 0; index < text.Length; index++)
{
if (random.Next(2) == 0)
{
result += text.Substring(index, 1).ToUpper();
}
else
{
result += text.Substring(index, 1).ToLower();
}
}

return result;
}
}

还有来自 MSDN :

"Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier."

这两者,尤其是每个站点上的代码示例(此处仅发布一个),似乎表明扩展方法必须至少有一个参数,因为该参数用于附加 this 关键字 to,允许该方法注册为它后面的类或类型的扩展。例如,

public static StringExtension(this String a) {/*stuff*/}

(如果是这种情况,那么这也意味着扩展方法中的第一个参数必须接受它正在扩展的类的实例,所以我可能错了。)

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