public class User
{
private string _username;
private string _password;
private Employee _employee;
//set get
}
public class Employee
{
private int _id;
private string _firstname;
private string _lastname;
//set get
}
問題是當我使用反射來迭代用戶類時,我無法識別Employee類。我的代碼是這樣的使用反射比較類
public string Compare<T>(T newVal, T oldVal)
{
StringBuilder retVal = new StringBuilder();
Type objectsType = typeof(T);
foreach (PropertyInfo propertyInfo in objectsType.GetProperties(
BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
{
//if (?) --> how to identify the propertyInfo here as class so that i can iterate using recursive
//{
// Compare(propertyInfo.GetValue(oldVal, null), propertyInfo.GetValue(newVal, null));
//}
if (propertyInfo.CanRead)
{
object newValue = propertyInfo.GetValue(newVal, null);
object oldValue = propertyInfo.GetValue(oldVal, null);
if (propertyInfo.PropertyType.Namespace.StartsWith("System") && !propertyInfo.PropertyType.IsGenericType)
{
if (!Object.Equals(newValue, oldValue))
{
retVal.Append(propertyInfo.Name + " = " + newValue.ToString() + ";");
}
}
}
}
return retVal.ToString();
}
請大家幫忙, 謝謝
問候, 威利
似乎有一些非常錯誤的做法。爲什麼不實施`IComparable`? – leppie 2011-01-25 05:03:50