C# 中的默认非索引器属性
如何在 C# 中创建默认的非索引器属性?
我的意思是我可以看到我可以创建索引器默认属性,如 此 MSDN 页面。
这允许我做类似的事情
Widgets widgets = new Widgets();
Widget result = widgets[1];
,但是如果我想实现类似 Nullable
所做的事情怎么办?
你可以在哪里采取
Nullable<decimal> nullDec = 1.23m;
decimal result = nullDec.Value;
OR
decimal result = (decimal)nullDec;
我认为这只是 nullDec.Value
的默认属性实现???
How can you create a default - non indexer - property in C#?
What I mean by this is I can see that I can create indexer default properties as illustrated on this MSDN page.
This allows me to do things like
Widgets widgets = new Widgets();
Widget result = widgets[1];
But what if I want to achieve something like what Nullable<T>
does?
Where you can take
Nullable<decimal> nullDec = 1.23m;
decimal result = nullDec.Value;
OR
decimal result = (decimal)nullDec;
Which I assume is simply a default property implementation to nullDec.Value
???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Nullable
在编译器中具有特殊处理,但您可以通过添加隐式或显式静态转换运算符来完成大部分操作。例如,对于类型
Foo
您可以添加一个运算符:允许:
和
Nullable<T>
has special handling in the compiler, but you can do most of that by adding implicit or explicit static conversion operators.For example, for type
Foo
you can add an operator:allowing:
and
如果您检查 Nullable{T} 的代码,您将看到显式强制转换实现如下所示:
所以是的,您是对的。
If you inspect the code of Nullable{T} you will see that the explicit cast implementation is like this:
So yes you are right.
Nullable
的实现方式是提供 显式转换运算符 到T
。所以也许您正在寻找类似的东西:
这可以让您这样做:
对我来说,这确实看起来像一个真正狡猾且不直观的API,所以我根本不建议这样做。为什么不只坚持使用标准索引器呢?
The way
Nullable<T>
does it is by providing an explicit conversion operator toT
.So perhaps you are looking for something like:
which would let you do:
This does look like a really dodgy and unintuitive API to me so I don't recommend doing this at all. Why not just stick to standard indexers?
不太确定我是否正确理解你的要求。在返回类型上实现强制转换运算符来实现您想要的效果还不够吗?
如果这不是您想要的,请解释一下。
Not very sure if I correct understant what you're asking for. Wouldn't be enough to implement cast operators on returning type to achieve what you want?
If it's not what you intend, please explain.
此类功能是编译器语法糖(在 IL 代码中,它们都转换为相同的低级代码),因此基本上在不修改 C# 编译器源代码的情况下不可能做到这一点。
Such kind of features are compiler syntactic sugar (in IL code they all are converted to same low level code), so basically it won't be possible to do this without modifying the C# compiler source.