10

次のようなことは可能ですか?

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

誰かがこれをやろうとした場合、

test tt = new test();
string asd = tt; // intercept this and then return something else
4

3 に答える 3

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.
   }
}

これにより、カスタム タイプのオブジェクトに文字列 (またはその他のタイプ) を割り当てて返すことができます (Fooここ)。

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

もちろん、2 つの暗黙的な変換演算子は対称である必要はありませんが、通常は対称であることが推奨されます。

注:変換演算子もありexplicitますが、暗黙の演算子の方が好きだと思います。

于 2010-03-01T03:03:09.190 に答える
2

カスタム型との間で暗黙的および明示的な変換演算子を定義できます。

public static implicit operator string(test value)
{
    return "something else";
}
于 2010-03-01T03:01:54.737 に答える
0

MikeP の回答を拡張すると、次のようなものが必要になります。

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

また

public static explicit operator Test( string value )
{
    //custom conversion routine
}
于 2010-03-01T03:05:17.927 に答える