我正在尝试将嵌套类传递给通用方法以评估其所有类,例如
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
}
因此,在我的第一个通用方法中,我将使用反射来:
看起来像这样:
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] 删除。
我来说两句