C# 泛型类型转换方法(.Net)

C# 泛型类型转换方法(.Net),c#,.net,types,C#,.net,Types,我正在尝试创建一个通用方法来投射对象,但似乎无法解决这个问题。(现在是周五下午3点,这是漫长的一周) 好的,我有一个场景: // We have a value (which .net sets as a double by default) object obj = 1.0; // We have the target type as a string, which could be anything: // say string sometType = "System.Decimal" T

我正在尝试创建一个通用方法来投射对象,但似乎无法解决这个问题。(现在是周五下午3点,这是漫长的一周)

好的,我有一个场景:

// We have a value (which .net sets as a double by default)
object obj = 1.0;

// We have the target type as a string, which could be anything:
// say string sometType = "System.Decimal"
Type type = Type.GetType(someType);

// I need a generic way of casting this
object castedObj = (xxx) obj;

如何在不创建无数if-else语句的情况下对该对象进行常规强制转换?

请查看该方法,我认为它将满足您的需要。

您无法将其强制转换为动态指定的类型

你可以考虑使用,但是我需要更多的代码来看看它对你有什么帮助。

你可以使用方法,如果你使用的类型是实现的(所有的原始类型都是)。
您可以执行以下操作:

    Type underlyingType = Type.GetType(someType);


    if (underlyingType.IsGenericType && underlyingType.GetGenericTypeDefinition().Equals(typeof (Nullable<>)))
    {
        var converter = new NullableConverter(underlyingType);
        underlyingType = converter.UnderlyingType;
    }

    // Try changing to Guid  
    if (underlyingType == typeof (Guid))
    {
        return new Guid(value.ToString());
    }
    return Convert.ChangeType(value, underlyingType);
Type underyingtype=Type.GetType(someType);
if(underyingtype.IsGenericType&&underyingType.GetGenericTypeDefinition().Equals(typeof(null)))
{
var转换器=新的NullableConverter(UnderlineType);
underlyingType=转换器。underlyingType;
}
//尝试更改为Guid
if(underlineType==typeof(Guid))
{
返回新的Guid(value.ToString());
}
返回Convert.ChangeType(值,underyingType);

更改类型函数的功劳

是否要将其类型转换为
type
变量表示的类型?您将如何申报castedObj?也就是说,你会给它什么类型的?如果将其存储为对象,则没有点类型转换…不能将装箱的int转换为int(或int?)以外的任何结构类型(有关详细信息,请参阅)。如果需要这样做,则需要使用转换以外的其他类型。
    Type underlyingType = Type.GetType(someType);


    if (underlyingType.IsGenericType && underlyingType.GetGenericTypeDefinition().Equals(typeof (Nullable<>)))
    {
        var converter = new NullableConverter(underlyingType);
        underlyingType = converter.UnderlyingType;
    }

    // Try changing to Guid  
    if (underlyingType == typeof (Guid))
    {
        return new Guid(value.ToString());
    }
    return Convert.ChangeType(value, underlyingType);