小编Fil*_*cur的帖子

对继承的泛型类型的反思

我在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); …
Run Code Online (Sandbox Code Playgroud)

c# generics reflection

4
推荐指数
1
解决办法
1819
查看次数

Visual Studio 2012如何绘制窗口边框?

如何使用Windows窗体在新的Visual Studio 2012主窗口中看到相同的alpha边框效果?它的窗户似乎发光.

c# winforms visual-studio-2012

2
推荐指数
1
解决办法
6402
查看次数

标签 统计

c# ×2

generics ×1

reflection ×1

visual-studio-2012 ×1

winforms ×1