c# - C# 中的默认非索引器属性

标签 c# properties language-features nullable default-value

如何在 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/

相关文章:

java - 属性文件点分隔的键名

c# - 关于 C# 语言规范中隐式转换的问题

c# - 使用 C#,如何获取我的机器是 64 位还是 32 位?

javascript - 在QML中解析属性和函数 "overrides"

eclipse - Eclipse 编辑器的只读属性 View

programming-languages - 有更好的C吗?

java - 如何实现 `range()`

c# - 如何为 64 位应用程序注册 .NET DLL

c# - 为什么 ZipFile.CreateFromDirectory 在此处拒绝访问?

c# - 用户可定义的布局(在运行时)