visual-studio 非静态方法需要 PropertyInfo.SetValue 中的目标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3577407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 12:22:55  来源:igfitidea点击:

Non-static method requires a target in PropertyInfo.SetValue

c#visual-studiogenericspropertyinfosetvalue

提问by Victor Gil

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

回答by Ronald Wildenberg

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

发生这种情况是因为default(T)返回null因为T表示引用类型。引用类型的默认值为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, MyClass2and its descendants must have a parameterless constructor now.

然后它会像你想要的那样工作。当然,MyClass2它的后代现在必须有一个无参数的构造函数。

回答by JaredPar

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

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

You'll need to do one of the following

您需要执行以下操作之一

  1. Pass a real instance of Tto the Test function to set the property values on
  2. Only set the static properties on the type
  1. 将 的真实实例传递T给 Test 函数以设置属性值
  2. 只在类型上设置静态属性

回答by user794791

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