我有一个像
这样的课程public class Stuff
{
public int A;
public float B;
public int C;
public float D;
public int E;
public List<float> AllMyFloats { get {/* how to grab B, D,... into new List<float>? */} }
}
如何抓取一个类型的所有内容(比如给定样本中的float
)并在属性访问时返回它们?
答案 0 :(得分:7)
反思是你的朋友。
public class Stuff
{
public int A { get; set; }
public float B { get; set; }
public int C { get; set; }
public float D { get; set; }
public int E { get; set; }
public List<float> GetAllFloats()
{
var floatFields = GetType().GetProperties()
.Where(p => p.PropertyType == typeof(float));
return floatFields.Select(p => (float)p.GetValue(this)).ToList();
}
}
class Program
{
static void Main()
{
Stuff obj = new Stuff() { A = 1, B = 2, C = 3, D = 4, E = 5 };
obj.GetAllFloats().ForEach(f => Console.WriteLine(f));
Console.ReadKey();
}
}
输出:
2
4
答案 1 :(得分:1)
你可以使用反射。
一些伪代码:
public List<float> AllMyFloats
{
get
{
var allMyFloats = new List<float>();
var properties = this.GetType().GetProperties();
foreach (var property in properties)
{
if (property.PropertyType == typeof(float))
{
//Get the value for the property on the current instance
allMyFloats.Add(property.GetValue(this, null));
}
}
return allMyFloats;
}
}