分配给类型为 System.Reflection.Missing through Reflection 的属性会引发异常

本文关键字:Reflection 属性 异常 Missing 类型 System 分配 through | 更新日期: 2023-09-27 18:37:06

我需要通过反射为属性赋值,到目前为止,除了System.Reflection.Missing类型的一种情况外,到目前为止测试的每个情况都可以。例如,这是类:

public class SomeClass
{
    public System.Reflection.Missing MissingProp { get; set; }
}

这是通过反射分配给属性的代码:

var inst = new SomeClass();
var prop = typeof (SomeClass).GetProperty("MissingProp");
prop.SetValue(inst, Missing.Value, null);

这是我收到的例外:

System.ArgumentException: Missing parameter does not have a default value.
Parameter name: parameters
   at System.Reflection.MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
   at ClassesWithNoProperties.Program.Main(String[] args) in D:'Documents'Documents'Visual Studio 2010'Projects'C#'ClassesWithNoProperties'ClassesWithNoProperties'Program.cs:line 24

我已经用太多的情况测试了我的库,这些情况使用相同的代码为属性赋值,这是我观察到这种行为的唯一情况(System.Reflection.Missing)。

如何在 C# 中实现此类分配?

分配给类型为 System.Reflection.Missing through Reflection 的属性会引发异常

错误消息不言自明 - Missing.Value 只能在具有可选参数的方法中用作占位符。您尝试执行的操作,在方法中使用它来使用 PropertyInformation 设置实例的值,根本没有意义,而 Missing.Value 知道这一点,因此它会引发异常。

奇怪的是,您可能可以使用 VB.Net 来使其工作,因为 VB.Net 支持默认参数。C# 没有。