我正在尝试使用扩展方法向C#StringBuilder类添加一个operater重载.具体来说,给定StringBuilder sb,我想sb += "text"成为等同于sb.Append("text").
以下是为以下内容创建扩展方法的语法StringBuilder:
public static class sbExtensions
{
public static StringBuilder blah(this StringBuilder sb)
{
return sb;
}
}
Run Code Online (Sandbox Code Playgroud)
它成功地将blah扩展方法添加到了StringBuilder.
不幸的是,运算符重载似乎不起作用:
public static class sbExtensions
{
public static StringBuilder operator +(this StringBuilder sb, string s)
{
return sb.Append(s);
}
}
Run Code Online (Sandbox Code Playgroud)
除其他问题外,this在此上下文中不允许使用关键字.
是否可以通过扩展方法添加运算符重载?如果是这样,那么正确的方法是什么?
可能重复:
在C#中重载复合赋值运算符的简单方法?
我正在玩事件,思想事件很奇怪.为什么我不能在泛型类中实现它们.所以我试着发现我不能超载+ =.从这里找到的语言规范
The overloadable unary operators are:
+ - ! ~ ++ -- true false
The overloadable binary operators are:
+ - * / % & | ^ << >> == != > < >= <=
Run Code Online (Sandbox Code Playgroud)
+ =未列出.现在,在你说没有理由重载之前+ =我想提出事实C#有使用+ =运算符的事件以及我试图实现一个有趣的事件并希望使用+ =运算符的事实.现在,我有一种感觉,有人会说这就是为什么事件存在,因为这是唯一的原因.但是我想提出你可以使用+ =与TimeSpan结构.去试试吧,var ts= new TimeSpan(); ts += ts;将编译并运行.
我查看了TimeSpan的定义,我不知道它是如何允许的.我看到了一个public static TimeSpan operator +(TimeSpan t);看起来很可疑的东西,但后来我意识到它var name = +ts;就像你怎么能做到var name = -ts;否定一样.
所以我的问题是,我如何使用+ =作为我的结构或类.它似乎得到支持我似乎无法找到它的文档.
我试图插入一个字符串,StringBuilder但我得到一个运行时错误:
抛出了类型'System.OutOfMemoryException'的异常.
为什么会发生这种情况?我该如何解决这个问题?
我的代码:
Branch curBranch("properties", "");
foreach (string line in fileContents)
{
if (isKeyValuePair(line))
curBranch.Value += line + "\r\n"; // Exception of type 'System.OutOfMemoryException' was thrown.
}
Run Code Online (Sandbox Code Playgroud)
执行分支
public class Branch {
private string key = null;
public StringBuilder _value = new StringBuilder(); // MUCH MORE EFFICIENT to append to. If you append to a string in C# you'll be waiting decades LITERALLY
private Dictionary <string, Branch> children = new Dictionary <string, Branch>();
public Branch(string nKey, string …Run Code Online (Sandbox Code Playgroud)