Activator.CreateInstance 带字符串

Activator.CreateInstance with string

我正在尝试从字段名称匹配的另一个 List< U > 填充通用 List< T >,类似于下面未经测试的伪代码。我遇到问题的地方是 T 是一个字符串,例如,它没有无参数构造函数。我试过将一个字符串直接添加到结果对象,但这给了我一个明显的错误——一个字符串不是类型 T。关于如何解决这个问题的任何想法?感谢指点。

    public static List<T> GetObjectList<T, U>(List<U> givenObjects)
    {
        var result = new List<T>();

        //Get the two object types so we can compare them.
        Type returnType = typeof(T);
        PropertyInfo[] classFieldsOfReturnType = returnType.GetProperties(
           BindingFlags.Instance |
           BindingFlags.Static |
           BindingFlags.NonPublic |
           BindingFlags.Public);

        Type givenType = typeof(U);
        PropertyInfo[] classFieldsOfGivenType = givenType.GetProperties(
           BindingFlags.Instance |
           BindingFlags.Static |
           BindingFlags.NonPublic |
           BindingFlags.Public);

        //Go through each object to extract values
        foreach (var givenObject in givenObjects)
        {

            foreach (var field in classFieldsOfReturnType)
            {
                //Find where names match
                var givenTypeField = classFieldsOfGivenType.Where(w => w.Name == field.Name).FirstOrDefault();

                if (givenTypeField != null)
                {
                    //Set the value of the given object to the return object
                    var instance = Activator.CreateInstance<T>();
                    var value = field.GetValue(givenObject);

                    PropertyInfo pi = returnType.GetProperty(field.Name);
                    pi.SetValue(instance, value);

                    result.Add(instance);
                }

            }
        }

        return result;
    }

如果 Tstring 并且您已经创建了将 givenObject 转换为字符串的自定义代码,您只需执行 intermediate castobject 将其添加到 List<T>:

    public static List<T> GetObjectList2<T, U>(List<U> givenObjects) where T : class
    {
        var result = new List<T>();

        if (typeof(T) == typeof(string))
        {
            foreach (var givenObject in givenObjects)
            {
                var instance = givenObject.ToString();  // Your custom conversion to string.
                result.Add((T)(object)instance);
            }
        }
        else
        {
            // Proceed as before
        }

        return result;
    }

顺便说一句,对于 T 的每个 属性,您要将 Tinstance 添加到 result ] 匹配 U 中的 属性 名称以及 givenObjects 中的每个项目。 IE。如果 givenObjects 是长度为 1 的列表并且 T 是具有 10 个匹配属性的 class,则 result 最终可能有 10 个条目。这看起来不对。此外,您需要注意 indexed properties.

作为此方法的替代方法,请考虑使用 Automapper,或使用 Json.NET 将 List<U> 序列化为 JSON,然后反序列化为 List<T>