我可以在结构上创建访问器以自动转换为/从其他数据类型转换吗?

cae*_*say 10 c# struct accessor

是否可以执行以下操作:

struct test
{
   this
   {
      get { /*do something*/ }
      set { /*do something*/ }
   }
}
Run Code Online (Sandbox Code Playgroud)

所以,如果有人试图这样做,

test tt = new test();
string asd = tt; // intercept this and then return something else
Run Code Online (Sandbox Code Playgroud)

Nol*_*rin 7

从概念上讲,你想在这里做什么实际上可以在.NET和C#中使用,但是你在语法方面咆哮了错误的树.这似乎是隐式转换运算符的解决方案,

例:

struct Foo
{
   public static implicit operator string(Foo value)
   {
      // Return string that represents the given instance.
   }

   public static implicit operator Foo(string value)
   {
      // Return instance of type Foo for given string value.
   }
}
Run Code Online (Sandbox Code Playgroud)

这允许您为自定义类型的对象(Foo此处)分配和返回字符串(或任何其他类型).

var foo = new Foo();
foo = "foobar";
var string = foo; // "foobar"
Run Code Online (Sandbox Code Playgroud)

当然,两个隐式转换运算符不必是对称的,尽管通常是可取的.

注意:还有explicit转换运算符,但我认为你更多的是隐式运算符.