如何使用reflection来查找实现特定接口的属性?
考虑这个例子:
public interface IAnimal { } public class Cat: IAnimal { } public class DoStuff { private Object catList = new List(); public void Go() { // I want to do this, but using reflection instead: if (catList is IEnumerable) MessageBox.Show("animal list found"); // now to try and do the above using reflection... PropertyInfo[] properties = this.GetType().GetProperties(); foreach (PropertyInfo property in properties) { //... what do I do here? // if (*something*) MessageBox.Show("animal list found"); } } }
你能完成if语句,用正确的代码替换一些东西吗?
编辑:
我注意到我应该使用属性而不是字段来实现这一点,所以它应该是:
public Object catList { get { return new List(); } }
你可以查看属性’ PropertyType
,然后使用IsAssignableFrom
,我假设你想要的是:
PropertyInfo[] properties = this.GetType().GetProperties(); foreach (PropertyInfo property in properties) { if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) { // Found a property that is an IEnumerable } }
当然,如果你想让上面的代码工作,你需要为你的类添加一个属性;-)
请注意,在您的示例中,使用GetType().GetProperties ()
找不到catList。 您可以使用GetType().GetFields ()
代替。
如果您要确定该属性是否定义为IEnumerable,则可以执行以下操作:
if (typeof(IEnumerable) == property.PropertyType) { MessageBox.Show("animal list found"); }
如果您想知道是否可以将属性的值分配给IEnumerable
,请执行以下操作:
if (typeof(IEnumerable).IsAssignableFrom (property.PropertyType)) { MessageBox.Show("animal list found"); }
如果属性类型不够具体(如object Animal{get;set;}
)以获得答案,则需要获取值来决定。 你可以这样做:
object value = property.GetValue(this, null); if (value is IEnumerable) { MessageBox.Show("animal list found"); }
另一种方法是从对象内部调用接口上的GetProperties()
,而不是对象本身。
public static void DisplayObjectInterface(object source, Type InterfaceName) { // Get the interface we are interested in var Interface = source.GetType().GetInterface(InterfaceName.Name); if (Interface != null) { // Get the properties from the interface, instead of our source. var propertyList = Interface.GetProperties(); foreach (var property in propertyList) Debug.Log(InterfaceName.Name + " : " + property.Name + "Value " + property.GetValue(source, null)); } else Debug.Log("Warning: Interface does not belong to object."); }
我喜欢将InterfaceName
参数设置为Type
以避免在按字符串名称查找GetInterface()
时出现任何拼写错误。
用法:
DisplayObjectInterface(Obj, typeof(InterFaceNameGoesHere));
编辑 :我刚刚注意到你的例子是一个集合,这对整个传递的集合无效。 您必须单独传递每个项目。 我很想删除,但这可能会帮助其他人在谷歌这个同样的问题寻找非收集解决方案。
上述就是C#学习教程:如何使用reflection来查找实现特定接口的属性?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1004297.html