通过反射获取属性 [英] Obtaining Properties with Reflection

查看:94
本文介绍了通过反射获取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出需要通用的对象,

例如:

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.


如果您读过这篇文章,您将会知道:):

泛型和反思 [
If you''ll read this you will know :) :

Generics and Reflection[^]

Regards,
Manfred


这篇关于通过反射获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆