3 回答
TA贡献1826条经验 获得超6个赞
当然,您可以在这里进行简单的转换(假设这是T型转换),如果方便的话(可以将其转换为T)转换:
public T CastExamp1<T>(object input) {
return (T) input;
}
public T ConvertExamp1<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
object value2a = Convert.ChangeType(value1, intType);
int value2b = Convert.ChangeType(value1, intType);
// Variable value3 is now an int with a value of 1000
dynamic value3 = Convert.ChangeType(value1, intType);
我已经用泛型写了答案,因为我想当您不处理实际类型而将其强制a something转换为代码时,很可能是代码气味的迹象a something else。使用适当的接口,在99.9%的时间中不必要。在反思中也许有一些边缘情况可能是有意义的,但我建议避免这些情况。
TA贡献1789条经验 获得超10个赞
其他答案没有提到“动态”类型。因此,要再添加一个答案,您可以使用“动态”类型存储生成的对象,而不必强制转换为静态类型的转换对象。
dynamic changedObj = Convert.ChangeType(obj, typeVar);
changedObj.Method();
请记住,使用“动态”编译器会绕过静态类型检查,如果不小心,可能会引入运行时错误。
- 3 回答
- 0 关注
- 348 浏览
添加回答
举报