![](/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.