[英]Default non indexer properties in C#
如何在C#中創建默認的-非索引器-屬性?
我的意思是,我可以看到可以創建此MSDN頁面上所示的索引器默認屬性。
這使我可以做類似的事情
Widgets widgets = new Widgets();
Widget result = widgets[1];
但是,如果我想實現類似Nullable<T>
功能怎么辦?
你可以去哪里
Nullable<decimal> nullDec = 1.23m;
decimal result = nullDec.Value;
要么
decimal result = (decimal)nullDec;
我認為這只是nullDec.Value
的默認屬性實現?
Nullable<T>
在編譯器中具有特殊處理,但是您可以通過添加隱式或顯式靜態轉換運算符來完成大多數操作。
例如,對於Foo
類型,您可以添加一個運算符:
public static implicit operator string(Foo value)
{
return "abc";
}
public static implicit operator Foo(int value)
{
...
}
允許:
Foo foo = ..
string s = foo; // uses string(Foo value)
和
int i = 123;
Foo foo = i; // uses Foo(int value)
如果檢查Nullable {T}的代碼,您將看到顯式強制轉換實現如下:
public static explicit operator T(Nullable<T> value)
{
return &value.Value;
}
所以是的,你是對的。
Nullable<T>
的方式是通過為T
提供顯式轉換運算符 。
因此,也許您正在尋找類似的東西:
public static explicit operator Widget(Widgets widgets)
{
// Argument checks here.
return widgets[0];
}
這會讓你做:
Widgets widgets = ..
Widget firstWidget = (Widget)widgets;
在我看來,這確實是一個非常狡猾且不直觀的API,因此我不建議您這樣做。 為什么不堅持使用標准索引器呢?
不太確定我是否糾正您的要求。 不足以在返回類型上實現強制轉換運算符以實現您想要的嗎?
如果不是您想要的,請解釋。
這類功能是編譯器語法糖(在IL代碼中,它們都被轉換為相同的低級代碼),因此,基本上,如果不修改C#編譯器源代碼就不可能做到這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.