gpt4 book ai didi

vb.net - 高效读取两个文本框

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:28:27 25 4
gpt4 key购买 nike

我正在用 VB.NET Winforms 编写一个程序,该程序采用习惯测量并将其转换为公制(SI 单位)。但是我需要读取用户在一个框中输入的单位以及在第二个框中输入的单位。例如,用户可以在一个框中输入“英尺”,然后在另一个框中输入“米”。我需要对此进行测试,使用开关但编写它效率太低。

'Not efficient:
Select Case CustomaryUnits.Text
Case CustomaryUnits.Text Is "Feet" And MetricUnit.Text Is "Meters"
'etc etc etc
End Select

我可以做什么?

最佳答案

我会做以下事情:

0) 保留文本框以输入数量/英尺/英寸/米等...
1) 使用下拉列表代替文本框。
2) 而不是仅仅将文本作为下拉列表的项目创建类并将它们添加为项目。下拉项将调用其 .ToString() 以获取项的文本值。
3) 所有这些项目都可以继承基类/抽象类,因此您可以传递数量值。

例如,您的下拉项可能是这样的:

我是 C# 用户,没有时间转换,所以这是我用 C# 代码表达的想法。

public abstract class MeasureableItem
{

public string Name { get; private set; }
public MeasureableItem(string name)
{
Name= name;
}
public abstract decimal ConvertFrom( MeasureableItem from, decimal qty);
public override string ToString() { return Name; }
}

然后您将定义一些类型:

public class Inches : MeasureableItem
{
public Inches() : base("Inches") {}
public override decimal ConvertFrom( MeasureableItem from, decimal qty)
{
if ( from is typeof(Feet) )
{
return qty * (decimal)12;
}
else{
throw new Exception("Unhandled conversion.");
}
}
}

public class Feet : MeasureableItem
{
public Feet() : base("Feet") {}

public override decimal ConvertFrom( MeasureableItem from, decimal qty)
{
if ( from is typeof(Inches) )
{
return qty / (decimal)12;
}
else{
throw new Exception("Unhandled conversion.");
}
}
}

您显然可以添加“else if { }”以支持更多转换。

要添加到下拉菜单,请执行以下操作:

MeasureableItem inches = new Inches();
MeasureableItem feet = new Feet();

dropDownFrom.Items.Add( inches);
dropDownFrom.Items.Add( feet);

您还必须为“收件人”下拉菜单创建一个专用实例,我认为这些控件不允许您在多个控件之间共享项目。

关于vb.net - 高效读取两个文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21322955/

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