2

希望是一个足够简单的问题,但我正在努力寻找答案。

如何将“对象”转换为“类型”对象中定义的类型。

例如,基本上我正在尝试通过反射执行以下操作,使其尽可能通用:

public class MyClass
{
    public string Prop1 { get; set; }
    public int Prop2 { get; set; }
}


public T FillMyClass<T>() where T : new()
{
    //The definitions here are suppled in code - each class we want to work with needs to be "mapped".
    string name1 = "Prop1";
    Type type1 = typeof(string);
    string name2 = "Prop2";
    Type type2 = typeof(int);

    //The values always start out as a string because of the way I'm receiving it.
    string val1 = "test";
    string val2 = "1";

    T t= new T();

    //Works fine, because val1 is already a string
    t.GetType().GetProperty(name1).SetValue(t, val1, null);

    //Having trouble with the below.
    object o = Convert.ChangeType(val2, type2);

    //Fails because o is not an int
    t.GetType().GetProperty(name2).SetValue(t, o, null);

}

所以类型是由用户定义的(或者甚至可能只是通过查找属性的类型)。但我只是看不到如何将对象转换为 [Type]。

4

1 回答 1

2

我也遇到过这个问题几次。虽然我确信有一个更优雅的解决方案来解决这个问题,但我已经制作了以下扩展方法来帮助您完成 99% 的工作。

    public static object TryConvertToType(this object source, Type destinationType, object defaultValue = null)
    {
        try
        {
            if (source == null)
                return defaultValue;

            if (destinationType == typeof(bool))
            {
                bool returnValue = false;

                if (!bool.TryParse(source.ToString(), out returnValue))
                {
                    return Convert.ChangeType(source.ToString() == "1", destinationType);
                }
                else
                {
                    return Convert.ChangeType(returnValue, destinationType);
                }
            }
            else if (destinationType.IsSubclassOf(typeof(Enum)))
            {
                try
                {
                    return Enum.Parse(destinationType, source.ToString());
                }
                catch
                {
                    return Enum.ToObject(destinationType, source);
                }
            }
            else if (destinationType == typeof(Guid))
            {
                return Convert.ChangeType(new Guid(source.ToString().ToUpper()), destinationType);
            }
            else if (destinationType.IsGenericType && destinationType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                Type genericType = destinationType.GetGenericArguments().First();

                return Convert.ChangeType(source, genericType);
            }
            else if (source.GetType().IsSubclassOf(destinationType))
            {
                return Convert.ChangeType(source, destinationType);
            }
            else if (!source.GetType().IsValueType
                && source.GetType() != typeof(string)
                && destinationType == typeof(string))
            {
                return Convert.ChangeType(source.GetType().Name, destinationType);
            }
            else
            {
                return Convert.ChangeType(source, destinationType);
            }
        }
        catch
        {
            return defaultValue;
        }
    }

基本上,在使用中,它是这样工作的:

t.GetType().GetProperty(name).GetValue(t, null).TryConvertToType(type2, 0);
于 2012-10-30T16:50:46.760 回答