2010-03-01 16 views
10

是否有可能做一些这样的:我可以在结构上创建访问器来自动转换为/从其他数据类型?

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

所以,如果有人试图做到这一点,

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

我不明白的问题。 – 2010-03-01 02:54:08

+0

@John Knoeller:更新了问题 – caesay 2010-03-01 02:58:04

+3

听起来像是你想要一个转换操作符... – Shog9 2010-03-01 02:58:40

回答

7

从概念上讲,你想在这里做什么,其实是.NET和C#中的可能,但你找错了树,关于语法。这似乎是一个implicit conversion operator是这里的解决方案,

例子:

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转换运算符,但我认为你更隐式运算符后。

+0

@sniperX:你必须根据字符串创建一个新的Foo实例。 – Shog9 2010-03-01 03:25:48

+0

是的,Shog9是对的。如果您不想直接公开构造函数,那么将它私有/保护就没有问题。 – Noldorin 2010-03-01 17:40:59

2

您可以定义implicitexplicit转换运营商,并从您的自定义类型。

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

扩展在MikeP's answer你想要的东西,如:

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

public static explicit operator Test(string value) 
{ 
    //custom conversion routine 
} 
相关问题