[英]How can I resolve the Class type for generic parameter, when the parameter value is being passed as an interface?
Consider a method with the following signature: 考虑具有以下签名的方法:
void foo(List<T> myList) ...
Let's assume, by using reflection, you need to construct such a function and obtain the PropertyInfo
details of the T
type parameter. 假设通过反射,您需要构造这样的函数并获取
T
类型参数的PropertyInfo
详细信息。 Calling typeof(T).GetProperties(...)
should do the trick, so we can add the following line to our method, to obtain these details. 调用
typeof(T).GetProperties(...)
应该可以解决问题,因此我们可以typeof(T).GetProperties(...)
添加到我们的方法中,以获取这些详细信息。
void foo(List<T> myList)
{
PropertyInfo[] props =
typeof(T).GetProperties(BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.FlattenHierarchy);
...
}
This provides the information we need... except when T
is an interface parameter, what I'm finding is that props
only contains the interface properties and not the properties associated with class that is within the list, which inherits from the interface. 这提供了我们需要的信息...除了当
T
是接口参数时,我发现的是props
仅包含接口属性,而不包含与列表中的类相关的属性,该类是从接口继承的。
To be clear, my interface AND my class definitions are public, as are the properties within my classes. 明确地说,我的接口和我的类定义是公共的,我的类中的属性也是公共的。
How can I get the properties associated with the actual type that inherits an interface rather than strictly the interface properties? 如何获得与继承接口的实际类型关联的属性,而不是严格地继承接口属性?
If you want the actual type, you probably need to get it for each item: 如果您想要实际的类型,则可能需要为每个项目获取它:
foreach (T t in myList)
{
Type itemType = t.GetType();
itemType.GetProperties(...)
// etc.
}
You can also add specific code for different types with: 您还可以使用以下方法为不同类型添加特定的代码:
if(itemType == typeof(MyConcreteType))
{
// do specific stuff for that type
}
If you want to get a flat list of all object properties contained inside the List<T>
, here's a LINQ solution: 如果要获取
List<T>
包含的所有对象属性的平面列表,请使用LINQ解决方案:
IEnumerable<PropertyInfo> properties =
myList.SelectMany(x => x.GetType()
.GetProperties(BindingFlags.Public |
BindingFlags.Instance));
If you need to access the declaring type, you can always look PropertyInfo.DeclaryingType
如果需要访问声明类型,则始终可以查看
PropertyInfo.DeclaryingType
If you don't want a flat list, Select
can do: 如果您不想使用固定列表,则“
Select
可以执行以下操作:
IEnumerable<PropertyInfo[]> properties =
myList.Select(x => x.GetType()
.GetProperties(BindingFlags.Public |
BindingFlags.Instance));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.