Skip type dynamically to <T>
I have such a situation ...
object myRoledata = List<Roles>() --> (some list or Ienumerable type)
Now I have a generic method that creates an XML object from List<T>- Something like this ..
public string GetXML<T>(object listdata)
{
List<T> objLists = (List<T>)Convert.ChangeType(listData, typeof(List<T>));
foreach(var obj in listdata)
{
//logic to create xml
}
}
Now, to run this method, I have to do like this:
string xml = GetXML<Roles>(myRoledata);
Now I do not know what Typecan come to me to pass a method GetXML. I have a method that will call GetXMLfor different ones Type, for example. Roles, Usersetc.
now i can get Typeinside List<>like this
Type genericType = obj.GetType().GetGenericArguments()[0];
but can't pass it like that
string xml = GetXML<genericType>(myRoledata);
Is there any way in which I can pass any method genericTypesto GetXML?
+5
Huzefa
source
share5 answers
, , , . , , .
:
public string GetXML(IEnumerable listdata) {
foreach(object obj in listdata)
//logic to create xml
}
... IEnumerable, "" :
public string GetXML(IEnumerable<object> listdata) {
foreach(object obj in listdata)
//logic to create xml
}
..., IEnumerable GetXML(someEnumerable.Cast<object>()) # 4.0 .
, .GetType() ( ):
public string GetXML(Type elementType, IEnumerable<object> listdata) {
foreach(object obj in listdata)
//logic to create xml
}
public string GetXML<T>(IEnumerable<T> listdata) {
return GetXML(typeof(T),listdata.Cast<object>());
}
, XML, , , : , - XElement xml .
+2