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
???
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:
public static implicit operator string(Foo value)
{
return "abc";
}
public static implicit operator Foo(int value)
{
...
}
allowing:
Foo foo = ..
string s = foo; // uses string(Foo value)
and
int i = 123;
Foo foo = i; // uses Foo(int value)
If you inspect the code of Nullable{T} you will see that the explicit cast implementation is like this:
public static explicit operator T(Nullable<T> value)
{
return &value.Value;
}
So yes you are right.
The way Nullable<T>
does it is by providing an explicit conversion operator to T
.
So perhaps you are looking for something like:
public static explicit operator Widget(Widgets widgets)
{
// Argument checks here.
return widgets[0];
}
which would let you do:
Widgets widgets = ..
Widget firstWidget = (Widget)widgets;
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.
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.
精彩评论