简体   繁体   中英

Activator.CreateInstance with string

I'm trying to populate a generic List< T > from another List< U > where the field names match, something like the untested pseudocode below. Where I'm having problems is when T is a string, for instance, which has no parameterless constructor. I've tried adding a string directly to the result object, but this gives me the obvious error -- that a string is not of Type T. Any ideas of how to solve this issue? Thanks for any pointers.

    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;
    }

If T is string and you have already created custom code to convert your givenObject to a string, you just need to do an intermediate cast to object to add it to a 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;
    }

Incidentally, you are adding an instance of T to result for every property of T that matches a property name in U and for every item in givenObjects . Ie if givenObjects is a list of length 1 and T is a class with 10 matching properties, result could end up with 10 entries. This looks wrong. Also, you need to watch out for indexed properties .

As an alternative to this approach, consider using Automapper , or serializing your List<U> to JSON with Json.NET then deserializing as a List<T> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM