Reflection - Call constructor with parameters

后端 未结 2 1768
没有蜡笔的小新
没有蜡笔的小新 2021-01-04 19:13

I read type from loaded assemblies for example:

var someType = loadedAssemblies
            .Where(a => a != null && a.FullName.StartsWith(\"MY.\"         


        
2条回答
  •  梦毁少年i
    2021-01-04 19:45

    You can make a helper method to get default value of a type:

    private static object GetDefaultValue(Type type)
    {
        if (type.IsEnum) return type.GetEnumValues().GetValue(0);
        if (type.IsValueType) return Activator.CreateInstance(type);
        return null;
    }
    

    Then, you can get default values of the parameters:

    var parameters = constructor.GetParameters()
                                .Select(p => GetDefaultValue(p.ParameterType))
                                .ToArray();
    

    And invoke the ConstructorInfo to get the instance:

    var obj = constructor.Invoke(parameters);
    

    If the constructor's parameters have default values and you want to use them, you can do something like this:

    var parameters = constructor
        .GetParameters()
        .Select(p => p.HasDefaultValue ? p.RawDefaultValue : GetDefaultValue(p.ParameterType))
        .ToArray();
    

提交回复
热议问题