对继承的泛型类型的反思

Fil*_*cur 4 c# generics reflection

我在c#中遇到了反射问题,但我找不到答案.

我有一个继承自泛型类的类,我试图从这个类中检索T的类型,但事实证明我不能!

这是一个例子:

class Products : List<Product>
{}
Run Code Online (Sandbox Code Playgroud)

问题是在运行时我不知道T的类型.所以我试着得到这样的类型:

Type itemsType = destObject.GetType().GetGenericArguments()[0]
Run Code Online (Sandbox Code Playgroud)

它没有成功.

这是我的方法:

public static object Deserialize(Type destType, XmlNode xmlNode)
    {         
        object destObject = Activator.CreateInstance(destType);

        foreach (PropertyInfo property in destType.GetProperties())
            foreach (object att in property.GetCustomAttributes(false))
                if (att is XmlAttributeAttribute)
                    property.SetValue(destObject, xmlNode.Attributes[property.Name].Value, null);
                else if (att is XmlNodeAttribute)
                {
                    object retObject = Deserialize(property.PropertyType, xmlNode.Nodes[property.Name]);
                    property.SetValue(destObject, retObject, null);
                }

        if (destObject is IList)
        {
            Type itemsType = destObject.GetType().GetGenericArguments()[0];
            foreach (XmlNode xmlChildNode in xmlNode.Nodes)
            {
                object retObject = Deserialize(itemsType, xmlNode);
                ((IList)destObject).Add(retObject);
            }
        }

        return destObject;
    }        
Run Code Online (Sandbox Code Playgroud)

我们的想法是读取一个xml文件并将其转换为一个对象:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SETTINGS>
  <PRODUCTS>
    <PRODUCT NAME="ANY" VERSION="ANY" ISCURRENT="TRUE" />
    <PRODUCT NAME="TEST1" VERSION="ANY" ISCURRENT="FALSE" />
    <PRODUCT NAME="TEST2" VERSION="ANY" ISCURRENT="FALSE" />
  </PRODUCTS>
  <DISTRIBUTIONS>
    <DISTRIBUTION NAME="5.32.22" />
  </DISTRIBUTIONS>
</SETTINGS>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,节点PRODUCTS将是我继承自List的集合

关于如何做到这一点的任何想法?

伙计们

SLa*_*aks 6

Products班是不是通用的,所以GetGenericArguments不返回任何东西.

您需要获取基类型的泛型参数,如下所示:

Type itemType = destObject.GetType().BaseType.GetGenericArguments()[0];
Run Code Online (Sandbox Code Playgroud)

但是,这不具有弹性; 如果引入了中间非泛型基类型,则它将失败.
相反,您应该找到实现的类型参数IList<T>.

例如:

Type listImplementation = destObject.GetType().GetInterface(typeof(IList<>).Name);
if (listImplementation != null) {
    Type itemType = listImplementation.GetGenericArguments()[0];
    ...
}
Run Code Online (Sandbox Code Playgroud)