gpt4 book ai didi

c# - 使用 C# 扩展方法重载运算符

转载 作者:IT王子 更新时间:2023-10-29 03:30:46 31 4
gpt4 key购买 nike

我正在尝试使用扩展方法将运算符重载添加到 C# StringBuilder 类。具体来说,给定 StringBuilder sb,我希望 sb += "text" 等效于 sb.Append("text ").

下面是为 StringBuilder 创建扩展方法的语法:

public static class sbExtensions
{
public static StringBuilder blah(this StringBuilder sb)
{
return sb;
}
}

它成功地将 blah 扩展方法添加到 StringBuilder

不幸的是,运算符重载似乎不起作用:

public static class sbExtensions
{
public static StringBuilder operator +(this StringBuilder sb, string s)
{
return sb.Append(s);
}
}

除其他问题外,此上下文中不允许使用关键字 this

是否可以通过扩展方法添加运算符重载?如果是这样,正确的做法是什么?

最佳答案

目前这是不可能的,因为扩展方法必须在静态类中,而静态类不能有运算符重载。但是 feature is being discussed for some future release of C# . Mads 谈了更多关于实现它的内容 in this video from 2017 .

C# 语言项目经理 Mads Torgersen 在谈到目前尚未实现的原因时说:

...for the Orcas release we decided totake the cautious approach and addonly regular extension methods, asopposed to extention properties,events, operators, static methods, etcetc. Regular extension methods werewhat we needed for LINQ, and they hada syntactically minimal design thatcould not be easily mimicked for someof the other member kinds.

We are becoming increasingly awarethat other kinds of extension memberscould be useful, and so we will returnto this issue after Orcas. Noguarantees, though!

在同一篇文章的下方:

I am sorry to report that we will notbe doing this in the next release. Wedid take extension members veryseriously in our plans, and spent alot of effort trying to get themright, but in the end we couldn't getit smooth enough, and decided to giveway to other interesting features.

This is still on our radar for futurereleases. What will help is if we geta good amount of compelling scenariosthat can help drive the right design.

关于c# - 使用 C# 扩展方法重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/172658/

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