如何在 C# 中创建默认的非索引器属性?
我的意思是我可以看到我可以创建索引器默认属性,如 this 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)
关于c# - C# 中的默认非索引器属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7537964/