这是强制转换和转换的示例:
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%的时间中不必要。在反思中也许有一些边缘情况可能是有意义的,但我建议避免这些情况。
一些额外的技巧: