mjs*_*jsr 13 .net c# extension-methods operator-overloading operators
是否可以定义一个同时是运算符的扩展方法?我想要一个固定的类添加使用实际上无法应用的已知运算符的可能性.对于这种特殊情况,我想这样做:
somestring++; //i really know that this string contains a numeric value
Run Code Online (Sandbox Code Playgroud)
我不想为所有代码传播类型转换.我知道我可以在字符串上创建包装类并定义该运算符但我想知道这种事情是否可以避免使用MySpecialString搜索和替换每个字符串声明.
编辑:因为大多数人说字符串是密封的,所以推导是不可能的,所以我修改"派生"到"包装",我的错误.
这在C#中是不可能的,但为什么不是标准的扩展方法呢?
public static class StringExtensions {
public static string Increment(this string s) {
....
}
}
Run Code Online (Sandbox Code Playgroud)
我认为somestring.Increment()更具可读性,因为你不会混淆真正不希望看到++应用于字符串的人.
小智 7
这个有用的明显例子是能够将TimeSpan类扩展为包含*和/运算符.
这是理想的工作......
public static class TimeSpanHelper
{
public static TimeSpan operator *(TimeSpan span, double factor)
{
return TimeSpan.FromMilliseconds(span.TotalMilliseconds * factor);
}
public static TimeSpan operator *(double factor, TimeSpan span) // * is commutative
{
return TimeSpan.FromMilliseconds(span.TotalMilliseconds * factor);
}
public static TimeSpan operator /(TimeSpan span, double sections)
{
return TimeSpan.FromMilliseconds(span.TotalMilliseconds / factor);
}
public static double operator /(TimeSpan span, TimeSpan period)
{
return span.TotalMilliseconds / period.TotalMilliseconds);
}
}
Run Code Online (Sandbox Code Playgroud)
不,你不能有一个也是运营商的扩展方法.扩展方法只能在静态类中声明,静态类不能有实例并且根据C#规范,
用户定义的运算符声明始终要求至少有一个参数属于包含运算符声明的类或结构类型.[7.3.2]
因此,扩展方法也不可能是重载操作符.
此外,您不能覆盖System.String,因为它是一个密封的类.
| 归档时间: |
|
| 查看次数: |
9979 次 |
| 最近记录: |