基于[Type]对象转换和转换对象

时间:2012-10-30 16:45:46

标签: c# reflection casting

希望这是一个简单的问题,但我很难找到答案。

我如何投射一个'对象'在'类型'中定义的类型对象

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

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]。

1 个答案:

答案 0 :(得分: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);
相关问题