I have the following two objects:
public class Dog
{
public string Name {get;set;}
public int Age {get;set;}
}
public class Person
{
public string Name {get;set;}
public string City {get;set;}
public string ID {get;set;}
}
Now, in the server side, I build a mix List of Person and Dog, and I would like to return this List to the client via web-service (asmx).
The order is important, and eventually my list will hold more types.
How can I return a list of mixed object in web-service?
Thank you.
I think you should create new class that encapsulate your many classes
public class Dog : MyClass
{
public string Name {get;set;}
public int Age {get;set;}
}
public class Person : MyClass
{
public string Name {get;set;}
public string City {get;set;}
public string ID {get;set;}
}
public class NewClass
{
public enum OBJType {
Dog,Person
} // like a constant for specific object type
public Dog D_Dog { get; set; }
public Person D_Person { get; set; }
public OBJType Type { get; set; }
public int seq { get; set; }
}
Then it should be use like this
//At Server
List<NewClass> newList = new List<NewClass>();
NewClass Item1 = new NewClass();
Item1.D_Dog = new Dog() { Name = "Woof", Age = 3 };
Item1.seq = 1;
Item1.Type = NewClass.OBJType.Dog;
newList.Add(Item1);
NewClass Item2 = new NewClass();
Item2.D_Person = new Person() { Name = "John", City = "TPP" , ID =111 };
Item2.seq = 2;
Item2.Type = NewClass.OBJType.Person;
newList.Add(Item2);
//At Client
List<NewClass> newList = //..get form webservice
foreach (var Item in newList)
{
if (Item.Type == NewClass.OBJType.Dog)
{
// using Item.D_Dog;
}
else {
// using Item.D_Person
}
}
Not a pro at C# so excuse if its not the most efficient.
1st class ie Person.cs
public class Person : MyClass
{
public string Name { get; set; }
public string City { get; set; }
public string ID { get; set; }
}
2nd Class ie Dog.cs
public class Dog : MyClass
{
public string Name { get; set; }
public int Age { get; set; }
}
The inherited class ie MyClass.cs
public class MyClass
{
public string Type { get; set; }
}
Notice I have added a field Type to differentiate between objects in the program consuming the webservice. You can improve this with enums for type.
The Example function to return the data.
public List<MyClass> returnData()
{
List<MyClass> returningdata = new List<MyClass>();
Person pers = new Person();
pers.City = "NELSPRUIT";
pers.Name = "TED";
pers.ID = "5502226585665";
pers.Type = "PERSON";
returningdata.Add(pers);
Dog doggy = new Dog();
doggy.Name = "Tiny";
doggy.Age = 2;
doggy.Type = "DOG";
returningdata.Add(doggy);
return returningdata;
}
Hope this is what you wanted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.