【问题标题】:C# Break down type parameter in generic method if its a nested classC#分解泛型方法中的类型参数,如果它是一个嵌套类
【发布时间】:2017-01-18 17:16:37
【问题描述】:

我正在尝试将嵌套类传递给泛型方法以评估其所有类,例如

SharedClass.FindParentClass<GrandParent.Parent.Child>();

通用方法:

public void FindParentClass<T>() where T: ISomeInterface, new()
{
  //Break down T to all of its classes
}

我想避免这样做:

SharedClass.FindParentClass<GrandParent,GrandParent.Parent,GrandParent.Parent.Child>();

适用于上述代码的通用方法:

public void FindParent<TGrandParent, TParent, TChild>() where TGrandParent : IGrandParent, new()
                                                         where TParent : IParent, new()
                                                          where TChild : IChild, new()
{
 //all I have to do now is place the type parameters there where I want them    
}

我不允许更改已用作类型参数的类,因此每个类都继承不同的接口并具有公共无参数构造函数。

【问题讨论】:

标签: c# generics nested


【解决方案1】:

为了按照我的预期工作,我必须编写另一个(私有)泛型方法来接受所有三个类型参数:

private void PerformWith<GrandParent, Grandparent.Parent, GrandParent.Parent.Child>()
{
         //Perform something
}

所以在我的第一个泛型方法中,我将使用反射来:

  1. 确定所有父类型 - 使用 GetTypeInfo().ReflectedType
  2. 要获取新方法,请将其设为泛型并调用它。

看起来像这样:

public void FindParentClass<T> where T: ISomeInterface, new()
{
   var parentClass = typeof(T).GetTypeInfo().ReflectedType;
   var grandparentClass = parentClass.GetTypeInfo().ReflectedType;

   var method = MethodBase.GetCurrentMethod().DeclaringType.GetMethod("PerformWith", BindingFlags.NonPublic());
   var genericMethod = method.MakeGenericMethod(new Type[] { grandparentClass, parentClass, typeof(T) });
   genericMethod.Invoke(null, null);
}

【讨论】:

    猜你喜欢
    • 2019-03-10
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    相关资源
    最近更新 更多