在我的节目,我有一个类示踪:C#如何将字符串转换为类的实例?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Tracepak_Heat_Loss_Program
{
class Tracer
{
public string family;
public string model;
public string type;
public int output;
public int voltage;
public int maxMaintain;
public int maxIntermittent;
public string tRating;
public string approvals;
public string code;
public Tracer(string f, string m, string t, int o, int v, int mM, int mI,string tR, string a, string c)
{
family = f;
model = m;
type = t;
output = o;
voltage = v;
maxMaintain = mM;
maxIntermittent = mI;
tRating = tR;
approvals = a;
code = c;
}
}
}
在我的主要形式,我已经创建了几个示踪剂的实例:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Tracepak_Heat_Loss_Program
{
public partial class mainForm : Form
{
public mainForm()
{
InitializeComponent();
}
private void mainForm_Load(object sender, EventArgs e)
{
}
Tracer J3 = new Tracer("Raychem BTV", "3BTV1-CT", "Self-Reg", 3, 120, 150, 185, "T6", "FM/CSA/ATEX", "J3");
Tracer J5 = new Tracer("Raychem BTV", "5BTV1-CT", "Self-Reg", 5, 120, 150, 185, "T6", "FM/CSA/ATEX", "J5");
Tracer J8 = new Tracer("Raychem BTV", "8BTV1-CT", "Self-Reg", 8, 120, 150, 185, "T6", "FM/CSA/ATEX", "J8");
Tracer J10 = new Tracer("Raychem BTV", "10BTV1-CT", "Self-Reg", 10, 120, 150, 185, "T6", "FM/CSA/ATEX", "J10");
我有我的主要形式的方法,它返回示踪名从列表框
public string GetTracer()
{
String s = tracerListBox.Text;
int index = s.IndexOf(" ");
return index >= 0 ? s.Substring(0, index): s;
}
// This could yield "J3" for example
我想能够使用GetTracer()的结果来检索该跟踪器的属性。
例如:
我可以打电话给
J3.family;
// The result of which is "Raychem BTV"
我想要做的是使用
GetTracer().family;
,并使其返回与示踪剂有关的财产,我的方法GetTracer回报。
这可能吗?预先感谢您的帮助。我对编程非常陌生,尽管我试图通过使用类来使代码更加健壮,但事实证明,这比我想象的要困难得多。
非常感谢您的回复。这对我来说是完美的解决方案,正是我想要完成的,它将大大提高这个特定程序的质量。干杯 – wcard 2012-02-22 19:56:19
林不知道是否有人会看到这一点,但只是为了确认我的理解:我的Tracer类中的ToString()方法允许我调用MessageBox.Show(tracer.family);没有错误? – wcard 2012-02-22 20:15:00
@wcard不,它的用途是仅用于在列表框中显示表示对象的字符串。 ListBox的'Items'集合包含所有对象('listBox.Items.Add(new Tracer(.....)')。只需移除'ToString'方法并测试你的代码。 – 2012-02-22 20:33:09