【问题标题】:C# Reflection - Get Generic Argument type of Super class from within the Base classC# 反射 - 从基类中获取超类的通用参数类型
【发布时间】:2020-03-12 17:29:41
【问题描述】:

考虑类:

public class Super : Base<Test, Super>
{
    public Super Next { get; set; }
}

public class Base<TArg, TSuper>
{
    public Type GetTestArgument()
    {
        Type[] arguments = typeof(TSuper).GetProperty("Next").PropertyType.BaseType.GetGenericTypeDefinition().GetGenericArguments();
        // arguments is set to [ TArg, TSuper ] instead of [ Test, Super ]
        return arguments[0]; // should be Test
    }
}

有谁知道如何在不调用typeof(TArg) 的情况下从基类中获取泛型类型,因为我将遍历其他超类属性,并且必须通过更深层次的反射。

谢谢。

【问题讨论】:

  • typeof(TArg)?
  • @Amy 我编辑添加了我忘记的信息。不过还是谢谢。

标签: c# inheritance reflection


【解决方案1】:

您可能不想拨打GetGenericTypeDefinition() 的电话。即:

typeof(TSuper).GetProperty("Next").PropertyType.BaseType.GetGenericArguments()

typeof(TSuper).GetProperty("Next").PropertyType.BaseType 返回类型 Base&lt;Test, Super&gt;。所以在它上面调用GetGenericArguments()会返回[Test, Super]

调用GetGenericTypeDefinition() 会得到Base&lt;TArg, TSuper&gt;,调用GetGenericArguments() 会返回[TArg, TSuper]

【讨论】:

  • 谢谢!愚蠢的错误!
猜你喜欢
  • 1970-01-01
  • 2013-12-16
  • 2010-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多