我试图将字符串转换为特定的类。字符串是类名。我有一个sql过程,返回三组数据,即客户端类的主记录。然后是辅助,地址类,最后是另一个辅助类,Contact class。
我使用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 :(得分:2)
您可以使用Activator.CreateInstance("your assemble name", "your class name")
方法。 here是更多信息
答案 1 :(得分: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 :(得分: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.