C# (CS0039) How to define conversion to a custom class from a string, with the `as` operator?

非 Y 不嫁゛ 提交于 2019-12-13 20:35:40

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!