C# - GetValue - 对象与目标类型不匹配

标签 c# generics reflection

我正在尝试编写一个通用方法来比较两个对象(我有意引入两种不同的类型。第二个具有与第一个相同的属性。第一个具有更多属性。)。

我想确保属性具有相同的值。以下代码适用于我在对象中拥有的大多数属性,但偶尔会抛出:

"Object Does Not Match Target Type"

...错误在

var valFirst = prop.GetValue(manuallyCreated, null) as IComparable;

public static bool SameCompare<T, T2>(T manuallyCreated, T2 generated){
var propertiesForGenerated = generated.GetType().GetProperties();
int compareValue = 0;

foreach (var prop in propertiesForGenerated) {

    var valFirst = prop.GetValue(manuallyCreated, null) as IComparable;
    var valSecond = prop.GetValue(generated, null) as IComparable;
    if (valFirst == null && valSecond == null)
        continue;
    else if (valFirst == null) {
        System.Diagnostics.Debug.WriteLine(prop + "s are not equal");
        return false;
    }
    else if (valSecond == null) {
        System.Diagnostics.Debug.WriteLine(prop + "s are not equal");
        return false;
    }
    else if (prop.PropertyType == typeof(System.DateTime)) {
        TimeSpan timeDiff = (DateTime)valFirst - (DateTime)valSecond;
        if (timeDiff.Seconds != 0) {
            System.Diagnostics.Debug.WriteLine(prop + "s are not equal");
            return false;
        }
    }
    else
        compareValue = valFirst.CompareTo(valSecond);
    if (compareValue != 0) {
        System.Diagnostics.Debug.WriteLine(prop + "s are not equal");
        return false;
    }
}

System.Diagnostics.Debug.WriteLine("All values are equal");
return true;
}

最佳答案

在 .NET 中为一个类型定义的每个属性都是不同的,即使它们具有相同的名称。你必须这样做:

foreach (var prop in propertiesForGenerated) 
{
    var otherProp = typeof(T).GetProperty(prop.Name);
    var valFirst = otherProp.GetValue(manuallyCreated, null) as IComparable;
    var valSecond = prop.GetValue(generated, null) as IComparable;

    ...

当然这没有考虑到 T 上定义的某些属性可能不存在于 T2 上,反之亦然。

关于C# - GetValue - 对象与目标类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17177671/

相关文章:

c# - 将非托管 dll 嵌入托管 C# dll

c# - 没有 EndExecuteNonQuery 的 BeginExecuteNonQuery

c# - 你如何从 Imgur 获取 access_token 和 refresh_token?

java - 填充和排序列表 <?扩展条款与条件>

c# - 我如何获得完成在其属性值中建立的要求的所有类属性?

c# - 用其他东西替换部分字符串

c# - 通用接口(interface)上的代码约定问题

Java 自动装箱和拆箱

android - Scala 反射 java.rmi 依赖,它可以在 Android 上工作吗?

java - 当参数是 Object[] 类型时通过反射调用方法