C#分解通用方法中的类型参数(如果它是嵌套类)

安妮

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

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    
}

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

安妮

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

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);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用嵌套在通用类中的类作为C#中的类型参数

C#反射-从基类中获取父类的通用参数类型

Scala:引用类的嵌套类型,它是泛型的类型参数

在C#中解析通用方法参数

通用类C#方法中的特例

无法从用法中推断出C#通用方法类型参数

在C#中应为通用接口基本类型时,如何传递方法参数?

通用类中的c#方法仅适用于某些类型

在 C# 中根据参数类型创建不同的通用对象

类型列表中的C#通用方法返回类型

子类中的 C# 方法是否可以具有不同的参数类型(从父类中的方法的参数类型派生)?

使用接口作为通用类的类型参数,但在C#中使用“类”的限制

为什么在通用类中不能有采用不同通用类型参数的方法?

基于通用类类型的类方法参数类型

多类的C#通用参数

在实现通用接口C#的通用类中修改值类型

限制通用子类方法可以在C#中接受的类型

在通用类中嵌套通用

如果它是odoo9中的通用类,则要继承哪个基类

从Kotlin中的嵌套类型参数获取类

具有不同通用参数的C#通用返回类型

C#通用方法,可以从表达式参数推断其类型参数

在通用go中模拟方法类型参数

如何约束通用类型参数以仅接受C#中的可为空的值类型?

C#中没有参数类型的方法参数

方法参数的通用类型

通用方法参数的类型

是否可以使接口方法返回带有C#中通用类型参数的另一个方法的类型?

在C#中将通用类型参数转换为特定类型