gpt4 book ai didi

c# - 我可以在结构上创建访问器以自动转换为其他数据类型或从其他数据类型转换吗?

转载 作者:可可西里 更新时间:2023-11-01 09:09:40 26 4
gpt4 key购买 nike

是否可以做类似下面的事情:

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# 中执行,但您在语法方面找错了树。好像是 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转换运算符,但我认为您更喜欢隐式运算符。

关于c# - 我可以在结构上创建访问器以自动转换为其他数据类型或从其他数据类型转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2353632/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com