[英]How Can I Modify The UInteger Type In Visual Basic .NET?
我要做的是创建一个名为Percent的结构。 它的范围是从0到100的整数,并且只能用于普通类型,即:
Dim a as Integer
所以:
Dim b as Percent
我尝试创建一个类,但我立刻明白Integer是一个结构,而不是一个类。 查看MSDN库我找不到多少。
解
Public Structure Percent Dim PValue As Integer Public Property Value As UInteger Get Return PValue End Get Set(ByVal value As UInteger) 'Make sure the value is valid... If value > 100 Then Throw New PercentTooBigException("You cannot give a percentage value greater than a 100.") ElseIf value < 0 Then Throw New PercentTooSmallException("You cannot give a percentage value smaller than 0.") End If '... and if it is set the local PValue to the value value. PValue = value End Set End Property End Structure
用法则为:Dim c as Percent Dim d as Percent c.Value = 99 d.Value = 26 If c.Value> d.Value Then End
我的解决方案中的骗局是你不能设置如下值:Dim e as Percent = 24相反,你需要访问Value属性并对其进行操作:Dim f as Percent f.Value = 23' (如上例所示)。
您可以使用扩展转换重载CType运算符以进行隐式转换。 您必须为要以此方式分配的每种类型重载它。
然后你可以使用这样的代码:
Dim pcnt As Percent = 42
Console.WriteLine("The percent is {0}%", pcnt)
码:
Public Structure Percent
Dim PValue As UInteger
Public Sub New(value As Integer)
Me.PValue = CType(value, UInteger)
End Sub
Public Property Value As UInteger
Get
Return PValue
End Get
Set(ByVal value As UInteger)
'Do something with invalid values
If value > 100 Then
PValue = 100
Else
If value < 0 Then
PValue = 0
Else
PValue = value
End If
End If
End Set
End Property
Public Overrides Function ToString() As String
Return PValue.ToString()
End Function
Public Shared Widening Operator CType(ByVal p As Integer) As Percent
Return New Percent(p)
End Operator
End Structure
这将是相当多的工作。 开始相对容易(为C#道歉):
public struct Percent
{
private uint pcnt;
public Percent(int value)
{
this.pcnt = (uint)value;
if (this.pcnt > 100)
{
throw new ArgumentOutOfRangeException("Value > 100");
}
}
public uint Value
{
get { return this.pcnt; }
set
{
if (value > 100)
{
throw new ArgumentOutOfRangeException("Value > 100");
}
this.pcnt = value;
}
}
}
这可以使用如下:
Percent p = new Percent(57);
Console.WriteLine("Value = {0}", p.Value);
Percent p2 = new Percent(44);
Console.WriteLine("Value = 0", p2.Value);
p2.Value = p.Value - 10;
你不能做的原因Percent p= 57;
因为虽然可以在VB或C#中为int等编写,但编译器特殊情况下它会在后台生成额外的代码。
现在努力工作开始了。 你想输入Percent p2 = p * p2
- 但我的问题是这是什么意思? 我们在上面的代码之后得到的两个值是57和47; 我认为将任何值乘以例如57%的百分比实际上乘以57 / 100.所以你必须通过乘法来决定你的意思,然后重写乘法运算并对其进行编码。 这也需要覆盖您可能想要使用的任何数字类型:int32,int64,decimal,uint32,uint64,您可能使用的任何其他类型。 完成所有这些后,您可以编写decimal adjusted = 123.45 * p;
然后,对于您可能想要使用的任何其他操作重复此操作,例如添加。 我可以看到一起添加两个百分比可能是有用的(如果它们总和大于100,会发生什么?),但是在int或其他数字中添加一个百分比? 那是做什么的?
相反,将一个百分比除以另一个百分比对我来说没有多大意义,但将百分比除以int(将int除以百分比)。
然后是需要实现的接口。 UInt实现了IComparable,IFormattable,IConvertible,IComparable和IEquatable。 您可能还应该实现这些(或者在您发现需要它们时做好准备)。
因此,找出所有操作的答案,编写操作覆盖代码,添加和实现您需要的接口,就在那里!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.