非静态方法需要一个目标对象来调用PropertyInfo.SetValue方法。

5

好的,我正在学习泛型,我试图让这个东西运行,但它一直报同样的错误。下面是代码:

public static T Test<T>(MyClass myClass) where T : MyClass2
{
    var result = default(T);
    var resultType = typeof(T);
    var fromClass = myClass.GetType();
    var toProperties = resultType.GetProperties();

    foreach (var propertyInfo in toProperties)
    {
        var fromProperty = fromClass.GetProperty(propertyInfo.Name);
        if (fromProperty != null)
            propertyInfo.SetValue(result, fromProperty, null );
    }

    return result;
}
3个回答

10
这是因为default(T)返回null,因为T表示引用类型。引用类型的默认值为null
您可以将方法更改为:
public static T Test<T>(MyClass myClass) where T : MyClass2, new()
{
    var result = new T();
    ...
}

然后它将按照您的要求工作。当然,MyClass2及其派生类现在必须具有无参数构造函数。


3
问题在于 T 是从 MyClass 派生出来的,因此是引用类型。因此,表达式 default(T) 将返回值 null。接下来对 SetValue 的调用将操作一个 null 值,但属性是实例属性,因此您会得到指定的消息。
您需要执行以下操作之一:
  1. 向 Test 函数传递 T 的实际实例以设置属性值
  2. 仅在类型上设置静态属性

1

不要使用

propertyInfo.SetValue(result, fromProperty, null);

尝试:

foreach (var propertyInfo in toProperties)  
{ 
    propertyInfo.GetSetMethod().Invoke(MyClass2, new object[] 
    { 
        MyClass.GetType().GetProperty(propertyInfo.Name).
        GetGetMethod().Invoke(MyClass, null)
    });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接