我有更新一些客户信息的方法
public UpdateCustomerInformationResponse UpdateCustomerInformation(UpdateCustomerInformationRequest request)
{
var customer = new Customer
{
FirstName = request.Customer
LastName = request.LastName,
MiddleInitial = request.MiddleInitial,
CustomerEmail = request.CustomerEmail,
UnitNumber = request.UnitNumber,
}
另一个对象
var fieldRequired = new FieldRequired{
FieldName = "CustomerEmail ",
IsRequired = 1
}
我想比较2个对象,以便我可以找出FieldName“CustomerEmail” 存在于Customer对象中。
答案 0 :(得分:0)
你的问题有点模糊。这是你在找什么?
if (fieldRequired.FieldName == "CustomerEmail" && fieldRequired.IsRequired == 1)
{
CustomerEmail = request.CustomerEmail;
}
答案 1 :(得分:0)
您可以实现IEqualtable接口,然后将方法设计为与要比较的数据成员相等。您可以在下面看到此实现的示例:
class Customer: IEquatable<Customer>
{
public string FirstName { get; set; }
public string LastName { get; set; }
...
public bool Equals(Person other)
{
return ((FirstName == other.FirstName) &&
(LastName == other.LastName));
}
}
答案 2 :(得分:0)
这么简单的伙伴。我找到了一个使用反射和扩散方法的简单解决方案,如下所示
创建一个名为“CompareTwoObjects”的静态类,并将代码添加到其中。
public static object CompareEquals(this T objectFromCompare, T objectToCompare)//Generic method
{
if (objectFromCompare == null && objectToCompare == null)
return true;
else if (objectFromCompare == null && objectToCompare != null)
return false;
else if (objectFromCompare != null && objectToCompare == null)
return false;
//Gets all the properties of the class
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
object dataFromCompare = objectFromCompare.GetType().GetProperty(prop.Name).GetValue(objectFromCompare, null);
object dataToCompare = objectToCompare.GetType().GetProperty(prop.Name).GetValue(objectToCompare, null);
Type type = objectFromCompare.GetType().GetProperty(prop.Name).GetValue(objectToCompare, null).GetType();
if (prop.PropertyType.IsClass && !prop.PropertyType.FullName.Contains("System.String"))
{
dynamic convertedFromValue = Convert.ChangeType(dataFromCompare, type);
dynamic convertedToValue = Convert.ChangeType(dataToCompare, type);
object result = CompareTwoObjects.CompareEquals(convertedFromValue, convertedToValue);
bool compareResult = (bool)result;
if (!compareResult)
return false;
}
else if (!dataFromCompare.Equals(dataToCompare))
return false;
}
return true;
}
这将使两个对象的结果具有相同的值。
用法: - Object1.CompareEquals(Object2的);
如果类对象很复杂,这也行。如果您发现任何问题,请回复