gpt4 book ai didi

c# - 如何声明结构的默认属性

转载 作者:行者123 更新时间:2023-11-30 16:18:47 24 4
gpt4 key购买 nike

我想用 struct 创建我自己的 Integer

这是一个 Integer 的简单示例,它的返回值被强制设置在 0 到 255 之间。

这些是伪代码,C# 不会编译它。

struct MyInt{
private int p;
default property theInt{
set{
p = value;
}
get{
if(p > 255) return 255; else if( p < 0) return 0;
return p;
}
}
}

我的主要目标是使用以下代码:

MyInt aaa = 300;            //Grater than 255
if(aaa == 255) aaa = -300; //Less than 255
if(aaa == 0) a = 50;

这可能与任何 .NET 语言有关吗?当然我更喜欢C#

最佳答案

正如我在评论中所说,您可以在结构和 int 之间使用隐式转换:

internal struct MyInt
{
private int p;

public int BoundedInt
{
// As CodesInChaos points out, the setter is not required here.
// You could even make the whole property private and jsut use
// the conversions.
get
{
if (p > 255) return 255;
if (p < 0) return 0;
return p;
}
}

public static implicit operator int(MyInt myInt)
{
return myInt.BoundedInt;
}

public static implicit operator MyInt(int i)
{
return new MyInt { p = i };
}
}

当你赋值时你需要 int-to-struct 转换和 struct-to-int 比较值时的转换。

关于c# - 如何声明结构的默认属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15875206/

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