【发布时间】: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# get parent from chlid instance。您可以使用反射确定声明对象的类型:.NET reflection - Get Declaring class type from instance property.
-
泛型只是单一类型的替代品,而不是文件中的类列表。没有通用约束来获取父类中的所有嵌套类。然而,这似乎很奇怪。为什么不简单地让所有嵌套类实现一个 commin 接口并将其用作约束呢?