Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

See i have a situation like this...

object myRoledata  = List<Roles>() --> (some list or Ienumerable type)

Now i have a generic method which 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 in order to run this method I have to do like this:

string xml = GetXML<Roles>(myRoledata);

Now i dont know what Type may come to me to be passed to GetXML method. I have a method which will call GetXML for different Types e.g. Roles, Users etc

now i can get the Type within the List<> like this

Type genericType = obj.GetType().GetGenericArguments()[0];

but cannot pass it like this

string xml = GetXML<genericType>(myRoledata);

Is there anyway in which i can pass any genericTypes to GetXML method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
223 views
Welcome To Ask or Share your Answers For Others

1 Answer

To do that, you need to use reflection;

typeof(SomeClass).GetMethod("GetXML").MakeGenericMethod(genericType)
         .Invoke(inst, new object[] {myRoleData});

where inst is null if it is a static method, this for the current instance (in which case you can also use GetType() instead of typeof(SomeClass)), or the target object otherwise.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...