我试图做操作符重载+=,但我不能.我只能让操作员超载+.
怎么会?
编辑
这不起作用的原因是我有一个Vector类(带有X和Y字段).请考虑以下示例.
vector1 += vector2;
Run Code Online (Sandbox Code Playgroud)
如果我的运算符重载设置为:
public static Vector operator +(Vector left, Vector right)
{
return new Vector(right.x + left.x, right.y + left.y);
}
Run Code Online (Sandbox Code Playgroud)
然后结果将不会添加到vector1,而是vector1也将通过引用成为全新的Vector.
我有一个主窗体的Windows窗体应用程序(从基础派生Form).可以在那里打开的其他模态形式来自我的类ManagedForm,它也来自Form.
此外,我有一个静态通知程序服务,它会触发这样的事件:
public static class NotifierService
{
public delegate void NotifierServiceEventHandler(object sender, NotifierServiceEventArgs e);
private static readonly object Locker = new object();
private static NotifierServiceEventHandler _notifierServiceEventHandler;
#region Events
public static event NotifierServiceEventHandler OnOk
{
add
{
lock (Locker)
{
_notifierServiceEventHandler += value;
if (
_notifierServiceEventHandler.GetInvocationList()
.Count(
_ =>
_.Method.DeclaringType != null &&
value.Method.DeclaringType != null &&
_.Method.DeclaringType == value.Method.DeclaringType) <= 1)
return;
_notifierServiceEventHandler -= value;
}
}
remove
{
lock (Locker)
{
_notifierServiceEventHandler -= …Run Code Online (Sandbox Code Playgroud) 您可以重载运算符true和false我查看了示例并找到了这个http://msdn.microsoft.com/en-us/library/aa691312%28v=vs.71%29.aspx
我完全不明白他们是如何工作的.我知道如果我写if(obj)并且true返回true则执行if.什么是错误的回报并不重要.但假工作怎么样?在该文档中,建议&&运算符使用它.我写了下面的代码.我不知道如何让&&编译.|| 也给了我一个编译错误.我怎么会被称为虚假?以及如何获得&&和|| 上班?
var ts= new MyTimeSpan();// ts += ts;
if (ts){ Console.WriteLine("Is true"); }
else { Console.WriteLine("not true"); }
//Console.WriteLine(ts && ts ? "Y" : "N");
class MyTimeSpan
{
public static MyTimeSpan operator +(MyTimeSpan t, MyTimeSpan t2) { return new MyTimeSpan(); }
public static bool operator true(MyTimeSpan t) { return true; }
public static bool operator false(MyTimeSpan t) { return false; }
}
Run Code Online (Sandbox Code Playgroud) 对于StringBuilder类,为什么不重载+ =运算符而不是使用唯一的.Append()方法?
Append()只连接字符串,为什么它们不只是像这样重载+ =运算符:
StringBuilder sb = new StringBuilder();
sb += "My string";
Run Code Online (Sandbox Code Playgroud)
这是效率的情况吗?是惯例还是直觉?
谢谢,
有没有人有一个非常简单的例子,说明如何在C#中重载复合赋值运算符?
这是一个tl;博士
我来自C++背景.&&假设检查左侧是否为真,右侧是否为真.与此有什么关系?为什么在&&逻辑中使用它?
我无法理解http://msdn.microsoft.com/en-us/library/aa691312%28v=vs.71%29.aspx并提出了一个问题.我花了很长时间才理解并接受这个答案.我不得不做很多跟进阅读操作员如何重载真假工作?
操作x && y被评估为T.false(x)?x:T.&(x,y)
为什么它这样做呢?如果false重载返回true并且true运算符返回true,则根本不计算y.WTF !!!!
我仍然无法理解它.因为这对我来说太奇怪了,我花了一些时间来理解另一个问题的答案.在C#v = 1 && 2;中不能正常工作你不能做&& on onts.在C中,这返回true(继承人代码/示例http://codepad.org/9iCaqzQ2).如果我们遵循上面的操作规则,我们会这样做
(使用1 && 2)
这会让你得到错误的结果.
那么...... C#以它的方式执行&&(和||)运算符的原因是什么.