Duc*_*een 2 .net c# reflection c#-5.0
我有一个类似的课程
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>? */} }
}
Run Code Online (Sandbox Code Playgroud)
如何获取一种类型的所有内容(比如float在给定的样本中)并在属性访问时返回它们?
反思是你的朋友.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
2
4
Run Code Online (Sandbox Code Playgroud)