您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用类型变量转换变量

使用类型变量转换变量

这是强制转换和转换的示例:

using System;

public T CastObject<T>(object input) {   
    return (T) input;   
}

public T ConvertObject<T>(object input) {
    return (T) Convert.ChangeType(input, typeof(T));
}

评论中的一些人说,这个答案不能回答问题。但是生产线(T) Convert.ChangeType(input, typeof(T))提供了解决方案。该Convert.ChangeType方法尝试将任何Object转换为第二个参数提供的Type。

例如:

Type intType = typeof(Int32);
object value1 = 1000.1;

// Variable value2 is Now an int with a value of 1000, the compiler 
// kNows the exact type, it is safe to use and you will have autocomplete
int value2 = Convert.ChangeType(value1, intType);

// Variable value3 is Now an int with a value of 1000, the compiler
// doesn't kNow the exact type so it will allow you to call any
// property or method on it, but will crash if it doesn't exist
dynamic value3 = Convert.ChangeType(value1, intType);

我已经用泛型写了答案,因为我想当您不处理实际类型而将其强制a something转换为代码时,很可能是代码气味的迹象a something else。使用适当的接口,在99.9%的时间中不必要。在反思中也许有一些边缘情况可能是有意义的,但我建议避免这些情况。

一些额外的技巧:

其他 2022/1/1 18:13:50 有553人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶