2014-03-28 43 views
0

我試圖將字符串轉換爲特定的類。該字符串是類名稱。我有一個sql過程返回三組數據,即客戶機類的主記錄。然後是Secondary,Address Class,最後是另一個Secondary類,Contact類。將字符串轉換爲類

我正在使用SqlDataReader來返回sql過程數據並使用reader.nextResults()來通過數據。

字符串值來自SQL過程。 例如:「地址」或「List_Contact」。

public static class Client 
{ 
    Guid Id { get; set;} 
    string ClientName { get; set;} 
    Address ClientAddress { get; set;} 
    List<Contact> ClientContacts { get; set;} 
} 

public static class Address 
{ 
    Guid Id { get; set;} 
    Guid ClientId { get; set;} 
    string AddressLine1 { get; set;} 
    string AddressLine2 { get; set;} 
    string AddressLine3 { get; set;} 
    string AddressLine4 { get; set;} 
    string PostalCode { get; set;} 
} 

public static class Contact 
{ 
    Guid Id { get; set;} 
    Guid ClientId { get; set;} 
    string ContactNumber { get; set;} 
    string ContactType { get; set;} 
} 

任何幫助將不勝感激。

謝謝。

+0

你解析逗號分隔的字符串和分配屬性?在這之後我很難過。更多的信息會很棒。謝謝。 – vikingben

+0

如果你有三個不同的結果集,爲什麼你需要類名?你不能只按照定義的順序處理結果集嗎? –

+0

你也可能想使用某種ORM系統,例如Dapper:https://code.google.com/p/dapper-dot-net/ – JleruOHeP

回答

1

編輯

我會用反射;

Dictionary<string, Type> dict = new Dictionary<string, Type>(); 
dict.Add("Foo", typeof(Foo)); 
dict.Add("Bar", typeof(Bar)); 

object obj = Activator.CreateInstance(dict[className]); 

... 

public class Foo 
{ 
    public Foo() 
    { 
     Console.WriteLine("new foo"); 
    } 
} 

public class Bar 
{ 
    public Bar() 
    { 
     Console.WriteLine("new bar"); 
    } 
} 

OLD

我會用switch聲明。

實施例:

object obj; 
switch(className) 
{ 
    case "Foo": 
     obj = new Foo(); 
     break; 
    case "bar": 
     obj = new Bar(); 
     break; 
    ... 
} 
2

可以使用Activator.CreateInstance("your assemble name", "your class name")方法。 here is more info

0

過了一段時間,字符串操作變得棘手。加上它可能不適用於你的情況,因爲沒有辦法連接實際的3個類。

看看這種做法是有道理的:

Dictionary<Guid, Client> clients = new Dictionary<Guid, Client>(); 

// first read all the Client records. 
while (reader.Read()) 
{ 
Guid clientId = Guid.Parse(reader["Id"].ToString()); 
Client tempClient = new Client(); 
tempClient.Contacts = new List<Contact>(); 
// construct the tempClient completely using all fields. 

clients.Add(clientId, tempClient); 
} 

// now move onto the address records. 
reader.nextResults(); 

while (reader.Read()) 
{ 
Guid clientId = Guid.Parse(reader["ClientId"].ToString()); 
clients[clientId].Address = new Address(); 
// construct the clients[clientId].Address completely using all fields. 
} 

// now move onto the contact records. 
reader.nextResults(); 

while (reader.Read()) 
{ 
Guid clientId = Guid.Parse(reader["ClientId"].ToString()); 
Contact tempContact = new Contact(); 
// construct the tempContact completely using all fields. 

clients[clientId].Contacts.Add(tempContact) 
} 

// at the end, the clients dictionary has all the Client objects linked with the right 
// Address and Contact objects. 
  1. SQL過程需要有3個選擇語句:客戶,解決&接觸。
  2. 在我們構建客戶端的代碼中。
  3. 然後,我們使用clientid地址字段將地址對象鏈接到正確的客戶端。
  4. 我們對聯繫人做同樣的事情。