通过反射获取属性

编程入门 行业动态 更新时间:2024-10-25 18:36:45
本文介绍了通过反射获取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出需要通用的对象, 例如:

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

更多推荐

通过反射获取属性

本文发布于:2023-11-12 11:42:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581406.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:反射   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!