问题
Is is possible to define (perhaps) an operator for a class which could enable using 'as' conversion?
The point is:
class C
{
string a;
string b;
public C what_here(string s)
{
a = s.Substring(0, 2);
b = s.Substring(3);
}
}
The class' use:
("something" as C).a;
This gives:
Error CS0039: Cannot convert type 'string' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
P.S. the true class C
is much bigger, the point is just how to enable the as
operator, which I just got used to...
回答1:
As per the docs for as
:
Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.
So you won't be able to use as
to invoke an implicit operator.
However, if you're prepared to use implicit or explicit casting:
class C
{
// Obviously you want to encapsulate these as properties, not fields
public string a;
public string b;
public static implicit operator C(string s)
{
var localA = s.Substring(0, 2);
var localB = s.Substring(3);
return new C
{
a = localA,
b = localB
};
}
}
void Main()
{
C myC = "AA BBBBBBBB"; // Or explicitly, var myC = (C)"AA BBBBBBBB"
Console.WriteLine(myC.a);
Console.WriteLine(myC.b);
}
Output:
AA
BBBBBBBB
But! Don't abuse the conversion operators
As per @Kieran's comment, conversion operators, when used in arbitrary ways, can be really difficult for others to read. It's not particularly intuitive that a string should automagically be converted into your own custom class. IMO the following alternatives are easier to read.
A constructor overload:
var myC = new C("string to parse here");
or an extension method:
var myC = "string to parse here".ToC();
where ToC
will be the same code as the conversion operator, but with the signature public static C ToC(this string s)
.
来源:https://stackoverflow.com/questions/55027875/c-sharp-cs0039-how-to-define-conversion-to-a-custom-class-from-a-string-with