动态获取参数类型的默认值

Chr*_*ard 8 c# reflection dynamic

我试图动态获取ParameterInfo中指定的类型的默认值._methods [methodName]返回一个MethodInfo对象.

不幸的是,编译器不喜欢默认(paramType)中的"paramType"位.我很难过.

错误

找不到类型或命名空间名称'paramType'(您是否缺少using指令或程序集引用?)

C:\ Applications\...\MessageReceiver.cs第113行

object blankObject = null;
foreach (var paramInfo in _methods[methodName].Key.GetParameters())
{
    if (paramInfo.Name == paramName)
    {
        Type paramType = paramInfo.ParameterType;
        blankObject = (object)default(paramType);
    }
}
parameters[i] = blankObject;
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 26

实现起来非常简单:

public object GetDefault(Type type)
{
    return type.IsValueType ? Activator.CreateInstance(type) : null;
}
Run Code Online (Sandbox Code Playgroud)

  • 不要太眩晕.他回答了_everyone'_问题!:) (6认同)