![](/img/trans.png)
[英]How can I use Reflection to get all fields of particular interface type
[英]How do I use reflection to get a list of values of an object's fields that match a particular type?
请注意,为了简洁和可读性,我已替换了更易于使用的类型,字段和方法。
我已经为类Person
定义了一个布尔属性personProperty
,在该类中我希望getter get{}
对在Person
中定义的每个整数字段值(在本例中为_age
personMethod(int arg)
调用私有方法personMethod(int arg)
, _phoneNumber
)。 它应该忽略所有其他类型,如readingList
。
这样,如果我要向Person
添加另一个整数字段(或修改或删除任何Person
字段名称),则不必更新personProperty
的定义,根据设计选择,该定义取决于Person
类的所有整数字段(即,永远不会让开发人员引入一个他不想让personMethod
运行的int
字段)。
public Class Person
{
private int _age;
public int _phoneNumber;
// protected int _futureInt;
Dictionary<string, string> _readingList = new Dictionary<string, string>();
public bool personProperty
{
get
{
// ...
bool personPropertyReturnValue;
List<bool> resultList = new List<bool>();
foreach(int personFieldValue in LISTOFPERSONINTS)
{
bool result = personMethod(personFieldValue);
resultList.Add(result);
}
// Do stuff with `resultList` that'll initialize personPropertyReturnValue;
return personPropertyReturnValue;
}
}
private bool personMethod(int arg)
{
bool returnValue = true;
// Do stuff to initialize `returnValue`
return returnValue;
}
}
我需要知道我应该代替LISTOFPERSONINTS
,使其返回了存储在值的迭代_age
, _phoneNumber
(以及其他所有未来int
,像_futureInt
中定义Person
)。
我不认为使用反射会比每次添加字段来调整属性都要好,但是您可以:
public class Person
{
private int _age;
public int _phoneNumber;
// protected int _futureInt;
Dictionary<string, string> _readingList = new Dictionary<string, string>();
public Person(int age){
_age = age;
}
public bool personProperty
{
get
{
List<bool> resultList = new List<bool>();
var intFields = this.GetType().GetFields(BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public)
.Where(f => f.FieldType == typeof(int))
.Select(f => f.GetValue(this)).Cast<int>();
foreach (int personFieldValue in intFields)
{
bool result = personMethod(personFieldValue);
resultList.Add(result);
}
// Do stuff with `resultList` that'll initialize personPropertyReturnValue;
bool personPropertyReturnValue = resultList.All(b => b);
return personPropertyReturnValue;
}
}
private bool personMethod(int arg)
{
return (arg > 0);
}
}
测试:
var person1 = new Person(0);
Console.WriteLine(person1.personProperty); // False
var person2 = new Person(1);
Console.WriteLine(person2.personProperty); // False
var person3 = new Person(1) { _phoneNumber = 1 };
Console.WriteLine(person3.personProperty); // True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.