泛型类型的递归函数

时间:2016-02-16 20:36:18

标签: c# class generics recursion types

我尝试编写一个递归函数函数,该函数将类作为参数并检查其所有成员,以确保所有成员都是字段类型或嵌套类型。该函数应调用自身以将嵌套类型成员作为参数。这是我失败的地方:

    private void Validate<C>() where C : class
    {
        MemberInfo[] x = typeof(C).GetMembers();
        for (int i = 0; i < x.Length; i++)
        {
            if (x[i].MemberType != MemberTypes.Field && x[i].MemberType != MemberTypes.NestedType)
            {
                throw new Exception(string.Format("Class members must be of type Field or NestedType"));
            }
//here I have problem sending 'a' as argument to the validate function 
      x.Where(a => a.MemberType == MemberTypes.NestedType).ToList().ForEach(a => Validate<typeof(a)>());
        }
    } 

2 个答案:

答案 0 :(得分:3)

更简单的解决方案是定义一个接受DbContext参数的私有方法重载:

TestServer

答案 1 :(得分:1)

您需要使用Reflection来使用正确的类型参数调用该方法:

typeof(YourClass)
    .GetMethod(nameof(Validate))
    .MakeGenericMethod(a.GetType())
    .Validate()