一个运算符重载的题目,请教大家! 在.net(C# or vb.net)中连接字符串可以用+号重载, 如 string s = "anne" + "rose";结果 s 值为"annerose", 类似的, 要在byte[] 类型实现同样的合并功能, 如byte[] b = {'a','n'} + {'n','e'}; 结果b的值为{'a','n','n','e'}. 请写出实现此重载功能的代码, 若不能请说明理由. 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 我想了一个晚上,没想到方法可以实现重载操作符。因为Byte是密封的,不能被继承。而操作符重载应该在内部定义。知识有限,恳请高人解答。 public static byte[] operator +(byte[] c1, byte[] c2){ byte[] c3=new byte[c1.Length+c2.Length]; c1.CopyTo(c3,0); c2.CopyTo(c3,c1.Length); return c3;} 没地方加 提示错误 哎~~~~,睡不着了,重载运算符必须是静态的,可能只能用类或结构来操作.程序小 ,就贴个完整的吧,using System;namespace zk{ public class OperatorTest { byte[] _b; public OperatorTest(byte[] bytes) { _b = bytes; } public static OperatorTest operator +(OperatorTest t1, OperatorTest t2) { byte[] b1 = new byte[t1._b.Length + t2._b.Length]; t1._b.CopyTo(b1,0); t2._b.CopyTo(b1,t1._b.Length); return new OperatorTest(b1); } public byte[] GetBytes() { return _b; } } public class OperatorDemo { public static void Main() { byte[] b1 = {1,2,3,4,5}; byte[] b2 = {6,7}; string s = null; OperatorTest t1 = new OperatorTest(b1); OperatorTest t2 = new OperatorTest(b2); OperatorTest t3 = t1 + t2; foreach (byte b in t3.GetBytes()) { s += b.ToString("") + ","; } System.Windows.Forms.MessageBox.Show(s.Substring(0,s.Length-1)); } }}//看卡通了哈.. em...楼上的给了个很好的启示我太死脑筋了。。老想着实现byte[]和byte[]笔直加。。结果想从Byte里继承出有重载的结构钻死角了 谢谢大家的帮助我很赞同redwolf_123(雨恨云愁) 的观点因为Byte是密封的,不能被继承。而操作符重载应该在内部定义。但是这是笔试题不知道他们道底想考什么呵呵还是谢谢大家!! Label.text 属性在主线程执行过程中动态更新显示问题 求教,c#如何在屏幕上显示消息? 上传问题,敬请高手赐教! 请教如何用GDI+实现画像皮线功能 c# 日期时间问题 UPDATE语句不会写 怎样在软件界面上放时钟(内详) object HTMLDIVeElement 为什么在dataGrid上按ctrl+c程序就歇菜了? 各位用C#开发的软件是不是都要把.NET framework一起发布出去? 请问各位大哥如何让listview中选定的一行处于编辑状态? C#以后会不会成为世界上最牛B的语言?期待高人解答...
而操作符重载应该在内部定义。
知识有限,恳请高人解答。
{
byte[] c3=new byte[c1.Length+c2.Length];
c1.CopyTo(c3,0);
c2.CopyTo(c3,c1.Length);
return c3;
} 没地方加 提示错误
重载运算符必须是静态的,可能只能用类或结构来操作.
程序小 ,就贴个完整的吧,
using System;
namespace zk
{
public class OperatorTest
{
byte[] _b;
public OperatorTest(byte[] bytes)
{
_b = bytes;
}
public static OperatorTest operator +(OperatorTest t1, OperatorTest t2)
{
byte[] b1 = new byte[t1._b.Length + t2._b.Length];
t1._b.CopyTo(b1,0);
t2._b.CopyTo(b1,t1._b.Length);
return new OperatorTest(b1);
}
public byte[] GetBytes()
{
return _b;
}
}
public class OperatorDemo
{
public static void Main()
{
byte[] b1 = {1,2,3,4,5};
byte[] b2 = {6,7};
string s = null;
OperatorTest t1 = new OperatorTest(b1);
OperatorTest t2 = new OperatorTest(b2);
OperatorTest t3 = t1 + t2;
foreach (byte b in t3.GetBytes())
{
s += b.ToString("") + ",";
}
System.Windows.Forms.MessageBox.Show(s.Substring(0,s.Length-1));
}
}
}
//看卡通了哈..
楼上的给了个很好的启示
我太死脑筋了。。
老想着实现byte[]和byte[]笔直加。。
结果想从Byte里继承出有重载的结构
钻死角了
因为Byte是密封的,不能被继承。
而操作符重载应该在内部定义。但是这是笔试题不知道他们道底想考什么呵呵
还是谢谢大家!!