所以我有一个包含字符串,浮点数,日期时间和数据表的类
public class Data : IEnumerator
{
string m_PowerSwitch = "Not Tested",
m_SerialNumber = "Not Tested",
m_Reset = "Not Tested",
m_WashPump = "Not Tested",
m_PortB = "Not Tested",
m_PortC = "Not Tested",
m_PortD = "Not Tested",
m_CurlyTube = "Not Tested",
m_BypassTube = "Not Tested";
float m_EC53115VMeasured = 0.0F,
m_EC53165VMeasured = 0.0F,
m_EC531624VMeasured = 0.0F,
m_SolventLineBVolumeMeasured = 0.0F,
m_SolventLineCVolumeMeasured = 0.0F,
m_SolventLineDVolumeMeasured = 0.0F,
m_CurlyTubeVolumeMeasured = 0.0F,
m_BypassTubeVolumeMeasured = 0.0F;
}
我想使用诸如
之类的foreach语句 foreach (ASM001.ASM asm in P00001.Global.ListofAvailableASMs)
{
if (asm.ASMData.EndTime == null)
asm.ASMData.EndTime = endTime;
foreach (object data in asm.ASMData)
{
if (data == "Not Tested")
{
asm.ASMData.Result = "FAILED";
}
continue;
}
但是我找不到任何帮助来搜索类的各个字段,只是在类类型的列表上。
我收到错误 foreach语句不能对类型' ASM001.Data'的变量进行操作。因为' ASM001.Data'不包含' GetEnumerator'
的公开定义我想知道这是否可行,或者我是否需要通过名称硬编码检查每个字符串字段并返回true或false。
就这样你现在有更多的字符串,而不是我要复制的字符串,这就是为什么我想知道是否有更快的方法来做。
答案 0 :(得分:3)
使用反射(代码释义,这不会构建)
Data data = ...
Type type = data.GetType();
FieldInfo[] fields = type.GetFields(...);
foreach(FieldInfo field in fields) {
Console.WriteLine("{0} = {1}", field.Name, field.GetValue( data ) );
}
答案 1 :(得分:1)
来自MSDN(以下示例应构建并运行):
以下示例检索MyClass的字段并显示 字段值。
using System;
using System.Reflection;
public class MyClass
{
public string myFieldA;
public string myFieldB;
public MyClass()
{
myFieldA = "A public field";
myFieldB = "Another public field";
}
}
public class FieldInfo_GetValue
{
public static void Main()
{
MyClass myInstance = new MyClass();
// Get the type of MyClass.
Type myType = typeof(MyClass);
try
{
// Get the FieldInfo of MyClass.
FieldInfo[] myFields = myType.GetFields(BindingFlags.Public
| BindingFlags.Instance);
// Display the values of the fields.
Console.WriteLine("\nDisplaying the values of the fields of {0}.\n",
myType);
for(int i = 0; i < myFields.Length; i++)
{
Console.WriteLine("The value of {0} is: {1}",
myFields[i].Name, myFields[i].GetValue(myInstance));
}
}
catch(Exception e)
{
Console.WriteLine("Exception : {0}", e.Message);
}
}
}
答案 2 :(得分:1)
可能的LINQ版本:
Data data = ...
FieldInfo[] fields = (from f in data.GetType().GetFields(BindingFlags.Instance|BindingFlags.NonPublic) where f.Name.StartsWith("m_") select f).ToArray();