次のようなことは可能ですか?
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"
もちろん、2 つの暗黙的な変換演算子は対称である必要はありませんが、通常は対称であることが推奨されます。
注:変換演算子もあり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
}