双向隐式运算符重载的模式和接口的名称
我最近发现了 C# 中隐式运算符重载的奇妙之处。我想知道,是否有两种隐式运算符重载的“方式”,例如:
public static implicit operator FooType(int num)
{
return new FooType(num);
}
public static implicit operator int(FooType fooType)
{
return fooType.IntValue;
}
- 该设计模式有名称吗?
- 是否有我可以使用的预定义 .NET 接口,例如
ICastable
?
I recently discovered the wonders of implicit operator overloading in C#. I was wondering, if you have both "ways" of implicit operator overloading, such as:
public static implicit operator FooType(int num)
{
return new FooType(num);
}
public static implicit operator int(FooType fooType)
{
return fooType.IntValue;
}
- Is there a name for that design pattern?
- Is there a predefined .NET interface that I can use, say
ICastable<int>
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知。
您可以考虑实施
IConvertible
。 (如果您的类也可以与事物进行比较,您可能会考虑实现IComparable
。)Not that I'm aware of.
You might consider implementing
IConvertible
. (If your class can also be compared to things, you might consider implementingIComparable<T>
.)