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

StackOverflow https://stackoverflow.com/questions/2353632

  •  23-09-2019
  •  | 
  •  

是否可以执行以下操作:

struct test
{
   this
   {
      get { /*do something*/ }
      set { /*do something*/ }
   }
}

所以如果有人试图这样做

test tt = new test();
string asd = tt; // intercept this and then return something else
有帮助吗?

解决方案

从概念上讲,你想在这里做什么,其实是内.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.
   }
}

这允许您指定和返回字符串(或任何其他类型)/从你的自定义类型(Foo这里)的物体。

var foo = new Foo();
foo = "foobar";
var string = foo; // "foobar"

两个隐式转换运营商不必是对称的,当然,虽然它通常是可取的。

注:也有 explicit 转换运营商,但我认为你隐运营商后会更。

其他提示

您可以定义 隐含的明确的 与您的自定义类型之间的转换运算符。

public static implicit operator string(test value)
{
    return "something else";
}

扩展在 MikeP的答案你想要的东西,如:

public static implicit operator Test( string value )
{
    //custom conversion routine
}

public static explicit operator Test( string value )
{
    //custom conversion routine
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top