这就是我在许多其他类继承的类中作为方法提出的.这个想法是它允许在相同类型的对象的属性之间进行简单比较.
现在,这确实有效 - 但为了提高我的代码质量,我想我会把它扔出去仔细检查.它怎么能更好/更有效/等等?
/// <summary>
/// Compare property values (as strings)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool PropertiesEqual(object comparisonObject)
{
Type sourceType = this.GetType();
Type destinationType = comparisonObject.GetType();
if (sourceType == destinationType)
{
PropertyInfo[] sourceProperties = sourceType.GetProperties();
foreach (PropertyInfo pi in sourceProperties)
{
if ((sourceType.GetProperty(pi.Name).GetValue(this, null) == null && destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null) == null))
{
// if both are null, don't try to compare (throws exception)
}
else if (!(sourceType.GetProperty(pi.Name).GetValue(this, null).ToString() == destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null).ToString()))
{
// only …Run Code Online (Sandbox Code Playgroud) 任何人都有一个好的实用程序类的建议,将值从一个对象映射到另一个对象?我想要一个使用反射的实用程序类,如果有一个具有相同名称的公共属性,它将获取两个对象并将值从第一个对象复制到第二个对象.
我有两个从Web服务代理生成的实体,所以我不能更改父类或者修改接口或类似的东西.但我知道这两个对象具有相同的公共属性.
Expression <>究竟在C#中使用了什么?是否有任何情况下您将Expression <>自己实例化为对象?如果是这样,请举个例子!
谢谢!
我从同一个类中获得了两个对象,我需要逐个字段地比较它们.问题在于它们有近百个字段,手工编写这些字段是很有帮助的.
你知道怎么做更简单的方法吗?Java中的反思可能是一个解决方案,但在我看来,它似乎是一个黑客.毕竟我寻求一个C#解决方案.
为了进行单元测试,我经常必须重写Equals和方法。GetHashCode之后我的课程开始看起来像这样:
public class TestItem
{
public bool BoolValue { get; set; }
public DateTime DateTimeValue { get; set; }
public double DoubleValue { get; set; }
public long LongValue { get; set; }
public string StringValue { get; set; }
public SomeEnumType EnumValue { get; set; }
public decimal? NullableDecimal { get; set; }
public override bool Equals(object obj)
{
var other = obj as TestItem;
if (other == null)
{
return false;
}
if (object.ReferenceEquals(this, …Run Code Online (Sandbox Code Playgroud) c# ×5
equals ×2
.net ×1
compare ×1
comparison ×1
expression ×1
gethashcode ×1
object ×1
overriding ×1
properties ×1