Exp*_*sam 5 c# variables properties
我知道属性可以设置为单一类型,并且一旦设置就不能更改,但是有没有办法创建 aproperty或 aproperty-like object来设置intwhile 返回 a string?
我不断创建像 an 这样的变量int,稍后将string仅使用它,而一旦设置就不再使用int。因此,在这种情况下,考虑到它不仅仅是一种类型到另一种类型,我总是必须进行大量转换。
也许像
struct strint
{
private int i; // 0 by default
public static implicit operator strint(int value) {
return new strint { i = value };
}
public static implicit operator string(strint value) {
return value.i.ToString();
}
public static implicit operator int(strint value) {
return value.i;
}
}
Run Code Online (Sandbox Code Playgroud)
使用示例:
strint a = 1;
a += 2; // 3
int i = a; // 3
string s = a; // "3"
Run Code Online (Sandbox Code Playgroud)