给出需要通用的对象, 例如:
Given an object that requires a generic, for example:
public class FetchMeWithReflection<T> { //Class Definition }是否可以收集"FetchMeWithReflection"的所有属性,而不管其泛型是什么? 例如:
Is it possible to gather all properties of "FetchMeWithReflection" regardless of the generic? for example:
public class OwningObject { public FetchMeWithReflection<string> StringInstance {get; set;} public FetchMeWithReflection<int> IntInstance {get; set;} public FetchMeWithReflection<OtherObject> OtherInstance {get; set;} }其他对象(或OwningObject本身知道它在哪个程序集中)是否可以收集这些属性? 类似于获取FetchMeWithReflection<object>并让它们全部获取(尽管我不认为这可行)
Can some other object (or the OwningObject itself knowing what assembly it is in) gather these properties? Something like fetching FetchMeWithReflection<object> and have it get them all (although I do not believe that works)
推荐答案我想我知道您要执行的操作.检查此代码是否有帮助: I think I know what you are trying to do. Check this code if it helps: OwningObject obj = new OwningObject(); PropertyInfo[] info = obj.GetType().GetProperties(); info.Where(x => x .PropertyType.Name.Contains("FetchMeWithReflection`1"));
上面的LINQ表达式的结果将具有类型FetchMeWithReflection的所有属性. 在OP的注释之后进行它指定了泛型类型所采用的类型参数的数量.
The result from the above LINQ expression will have all the properties of type FetchMeWithReflection. Edit after OP''s comment: It specifies the number of type paramters the generic type takes in.
如果您读过这篇文章,您将会知道:): 泛型和反思 [ ^ ] 问候, 曼弗雷德(Manfred) If you''ll read this you will know :) : Generics and Reflection[^] Regards, Manfred
更多推荐
通过反射获取属性
发布评论