【问题标题】:Non-static method requires a target in PropertyInfo.SetValue非静态方法需要 PropertyInfo.SetValue 中的目标
【发布时间】:2023-03-10 23:45:02
【问题描述】:

好的,所以我正在学习泛型,我正在尝试让这个东西运行,但它一直告诉我同样的错误。代码如下:

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;
}

【问题讨论】:

    标签: c# visual-studio generics propertyinfo setvalue


    【解决方案1】:

    这里的问题是T 派生自MyClass,因此是一个引用类型。所以表达式default(T) 将返回值null。以下对 SetValue 的调用正在操作 null 值,但该属性是实例属性,因此您会收到指定的消息。

    您需要执行以下操作之一

    1. T 的真实实例传递给Test 函数以设置属性值
    2. 只设置类型的静态属性

    【讨论】:

      【解决方案2】:

      这是因为default(T) 返回null,因为T 代表一个引用类型。引用类型的默认值为null

      您可以将方法更改为:

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

      然后它将按您的意愿工作。当然,MyClass2 及其后代现在必须有一个无参数的构造函数。

      【讨论】:

        【解决方案3】:

        代替

        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)
            });
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-11-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多