在我的節目,我有一個類示蹤: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