Non-static method requires a target in PropertyInfo.SetValue
Asked Answered
V

3

5

Ok, so I'm learning about generics and I'm trying to make this thing run, but its keep saying me the same error. Here's the code:

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;
}
Vhf answered 26/8, 2010 at 16:49 Comment(0)
I
10

This happens because default(T) returns null because T represents a reference type. Default values for reference types are null.

You could change your method to:

public static T Test<T>(MyClass myClass) where T : MyClass2, new()
{
    var result = new T();
    ...
}

and then it will work as you want it to. Of course, MyClass2 and its descendants must have a parameterless constructor now.

Idolize answered 26/8, 2010 at 16:54 Comment(0)
B
3

The problem here is that T derives from MyClass and is hence a reference type. So the expression default(T) will return the value null. The following call to SetValue is operating an a null value but the property is an instance property hence you get the specified message.

You'll need to do one of the following

  1. Pass a real instance of T to the Test function to set the property values on
  2. Only set the static properties on the type
Brackett answered 26/8, 2010 at 16:53 Comment(0)
T
1

Instead of

propertyInfo.SetValue(result, fromProperty, null);

try:

foreach (var propertyInfo in toProperties)  
{ 
    propertyInfo.GetSetMethod().Invoke(MyClass2, new object[] 
    { 
        MyClass.GetType().GetProperty(propertyInfo.Name).
        GetGetMethod().Invoke(MyClass, null)
    });
}
Tayler answered 1/9, 2011 at 20:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.