将动态输入到< T>
请参阅我有一个像这样的情况......
See i have a situation like this...
object myRoledata = List<Roles>() --> (some list or Ienumerable type)
现在我已经从列表< 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 Type
s 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任何
,并在C#4.0甚至直接由协方差的IEnumerable
调用( someEnumerable.Cast<对象>())
... 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.