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

时间:2021-03-15 17:07:33

Question

I am trying to dynamically get the default for a type that is specified in a ParameterInfo. _methods[methodName] returns a MethodInfo object.

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

Unfortunately, the compiler doesn't like the "paramType" bit inside the default(paramType). I'm stumped.

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

Error

The type or namespace name 'paramType' could not be found (are you missing a using directive or an assembly reference?)

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

C:\Applications\...\MessageReceiver.cs Line 113

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

Example

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;

2 个解决方案

#1


It's quite simple to implement:

实现起来非常简单:

public object GetDefault(Type type)
{
    return type.IsValueType ? Activator.CreateInstance(type) : null;
}

#2


I think default only works with the an actual type. It's a complier shortcut not an actual method. It works well with generics. for example:

我认为默认只适用于实际类型。它是一个编译器快捷方式而不是实际方法。它适用于泛型。例如:

public void MyMethod<T>(T obj)
{
   T myvar = default(T);
}

Check out this question I posted a while back:

看看我发布的这个问题:

Default Value for Generics

泛型的默认值

#1


It's quite simple to implement:

实现起来非常简单:

public object GetDefault(Type type)
{
    return type.IsValueType ? Activator.CreateInstance(type) : null;
}

#2


I think default only works with the an actual type. It's a complier shortcut not an actual method. It works well with generics. for example:

我认为默认只适用于实际类型。它是一个编译器快捷方式而不是实际方法。它适用于泛型。例如:

public void MyMethod<T>(T obj)
{
   T myvar = default(T);
}

Check out this question I posted a while back:

看看我发布的这个问题:

Default Value for Generics

泛型的默认值