开发者

Can I create accessors on structs to automatically convert to/from other datatypes?

开发者 https://www.devze.com 2022-12-21 18:18 出处:网络
is it possible to do something like the following: struct test { this { get { /*do something*/ } set { /*do something*/ }

is it possible to do something like the following:

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

so that if somebody tried to do this,

test tt = new test();
string asd = tt; // int开发者_如何学Goercept this and then return something else


Conceptually, what you want to do here is in fact possible within .NET and C#, but you're barking up the wrong tree with regards to syntax. It seems like an implicit conversion operator would be the solution here,

Example:

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

This allows you to assign and return strings (or any other type) to/from objects of your custom type (Foo here).

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

The two implicit conversion operators don't have to be symmetric of course, though it's usually advisable.

Note: There are also explicit conversion operators, but I think you're more after implicit operators.


You can define implicit and explicit conversion operators to and from your custom type.

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


Expanding on MikeP's answer you want something like:

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

or

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号