我想將屬性名和匹配數據寫入分隔文件,我從c#objectdumper幫助文件複製了一些代碼,它似乎都可以正常工作,但我不理解反射足以有信心使用它。我擔心的是一個錯誤的值被放在不正確的列中,是否有可能發生這種情況,例如,使用反射將類保存到delim文件
Field1,Field2
Val1,Val2
Val1,Val2
Val2,Val1 << Could this ever happen ?
此外,這段代碼是什麼意思?下面
f != null ? f.GetValue(this) : p.GetValue(this, null)
代碼:
public string returnRec(bool header, string delim)
{
string returnString = "";
bool propWritten = false;
MemberInfo[] members = this.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance);
foreach (MemberInfo m in members)
{
FieldInfo f = m as FieldInfo;
PropertyInfo p = m as PropertyInfo;
if (f != null || p != null)
{
if (propWritten)
{
returnString += delim;
}
else
{
propWritten = true;
}
if (header)
returnString += m.Name;
else
{
Type t = f != null ? f.FieldType : p.PropertyType;
if (t.IsValueType || t == typeof(string))
{
returnString += f != null ? f.GetValue(this) : p.GetValue(this, null);
}
}
}
}
return returnString;
}
謝謝,雖然它可能只會節省幾秒鐘,我會使用它。 – 2009-08-01 22:22:15