将动态输入到< T> [英] Pass Type dynamically to <T>

查看:80
本文介绍了将动态输入到< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅我有一个像这样的情况......

See i have a situation like this...

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

现在我已经从<$创建一个XML对象的通用方法C $ C>列表< T> -
这样的事情。

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);

现在我不知道是什么键入可能会我要传递给的getXML 方法。我有一个称之为的getXML 不同的键入取值例如方法角色用户

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

现在我可以得到键入列表与LT内;> 像这样

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);



反正我在其中可以通过任何 genericTypes 的getXML 方法?

推荐答案

这是一个问题,你可能想的避免的解决。它的的可能,通过反射,动态调用方法,而静态地解决这些问题 - 但它种违背了类型标注整点

This is a problem you probably want to avoid solving. It is possible, via reflection, to call methods dynamically without statically resolving them - but it kind of defeats the whole point of the type-annotations.

做这一点:

public string GetXML(IEnumerable listdata) {  
    foreach(object obj in listdata)   
        //logic to create xml  
}

...你现在可以与任何的IEnumerable 打电话或写出来的现代的方式:

... which you now can call with any IEnumerable, or write it the "modern" way as:

public string GetXML(IEnumerable<object> listdata) {  
    foreach(object obj in listdata)   
        //logic to create xml  
}

...您可以通过的getXML任何的IEnumerable 调用( someEnumerable.Cast<对象>()),并在C#4.0甚至直接由协方差

... which you can call with any IEnumerable via GetXML(someEnumerable.Cast<object>()) and in C# 4.0 even directly by covariance.

如果你需要一个元素运行时的类型,你可以得到它使用 .GetType()每个元素,或者你可以通过它作为一个参数(并提供向后兼容的覆盖):

If you need the type of an element runtime, you can get it using .GetType() on each element, or you can just pass it in as a parameter (and provide an override for backwards-compatibility):

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的有效性保证的引导

Incidentally, if you're constructing XML, a string is probably a less robust return-type choice: if possible, you could work with something like an XElement instead - and get xml-validity guarantee's to boot.

这篇关于将动态输入到&lt; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆