The line does not work

Consider this class:

public class MyString
{
 private string _string;

 public string String
 {
  get { return _string; }
  set { _string = value; }
 }

 public MyString(string s)
 {
  _string = s;
 }

 public static implicit operator string(MyString str)
 {
  return str.String;
 }

 public static implicit operator MyString(string str)
 {
  return new MyString(str);
 }
}

How do I make the following code?

MyString a = "test";
object b = a;
var c = (string)b;

Now I get this exception:

InvalidCastException: Cannot cast object of type "MyString" to type "System.String".

+5
source share
4 answers

Custom cast is a hidden feature. Whether the actual execution is being executed or a custom conversion operator is called depends on the type of compilation time of the expression being expressed.

, Ie. b object, object . .

MyString a = "test";
object b = a;
var c = (string)b;
string d = a;
var e = (string)a;

  // ,   string d = MyString.op_implicit (a);

. , , , .

. , , , . (string)a , , , a, . , MyString, ( , ).

, , ( ) , , . ( ), ,

+2

/ - object. , . :

string s = a;
+4

You can try changing the last line to:

string c = (string)((MyString)b);
+2
source

You must try:

public MyString:String
{
//code
}
-1
source

All Articles