Ste*_*uer 13 .net c# reflection interface
考虑这个例子:
public interface IAnimal
{
}
public class Cat: IAnimal
{
}
public class DoStuff
{
private Object catList = new List<Cat>();
public void Go()
{
// I want to do this, but using reflection instead:
if (catList is IEnumerable<IAnimal>)
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
你能完成if语句,用正确的代码替换一些东西吗?
编辑:
我注意到我应该使用属性而不是字段来实现这一点,所以它应该是:
public Object catList
{
get
{
return new List<Cat>();
}
}
Run Code Online (Sandbox Code Playgroud)
dri*_*iis 15
你可以查看属性' PropertyType,然后使用IsAssignableFrom,我假设你想要的是:
PropertyInfo[] properties = this.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
if (typeof(IEnumerable<IAnimal>).IsAssignableFrom(property.PropertyType))
{
// Found a property that is an IEnumerable<IAnimal>
}
}
Run Code Online (Sandbox Code Playgroud)
当然,如果你想让上面的代码工作,你需要为你的类添加一个属性;-)
| 归档时间: |
|
| 查看次数: |
8311 次 |
| 最近记录: |