C# 通过反射指定System.Reflection.Missing类型的属性会引发异常

C# 通过反射指定System.Reflection.Missing类型的属性会引发异常,c#,.net,reflection,properties,C#,.net,Reflection,Properties,我需要通过反射为属性赋值,到目前为止,除了System.reflection.Missing类型的情况外,所有测试的情况都没有问题。例如,这是一个类: public class SomeClass { public System.Reflection.Missing MissingProp { get; set; } } 这是通过反射分配给属性的代码: var inst = new SomeClass(); var prop = typeof (SomeClass).GetProper

我需要通过反射为属性赋值,到目前为止,除了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语言中实现这种赋值?

错误消息是不言自明的-缺少的.Value只能在具有可选参数的方法中用作占位符。您试图在方法中使用它来设置使用PropertyInfo的实例的值,这完全没有意义,并且丢失了。value知道这一点,因此会引发异常


奇怪的是,您可能可以使用VB.Net来实现这一点,因为VB.Net支持默认参数。C没有。

我如何用C完成这种任务?很简单,你不能。通过在任何方法中将Missing.Value作为参数传递,可以指示编译器将Missing.Value替换为该参数的默认值。因此,在调用prop.SetValue时将Missing.Value作为Value参数传入会导致代码失败,因为SetValue方法签名中的Value参数没有默认值。