Zyp*_*rax 185
当然你可以在这里既简单(假设这是一个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%的时间不应该是必需的.在反思中可能有一些边缘情况可能有意义,但我建议避免这些情况.
mau*_*k13 103
其他答案没有提到"动态"类型.因此,要再添加一个答案,可以使用"动态"类型来存储生成的对象,而无需使用静态类型转换转换对象.
dynamic changedObj = Convert.ChangeType(obj, typeVar);
changedObj.Method();
请记住,使用"动态"编译器会绕过静态类型检查,如果不小心,可能会引入可能的运行时错误.
bal*_*age 19
这是我的方法来转换对象而不是通用类型变量,而不是System.Type动态:  
我在运行时使用System.Linq.Expressions类型的方法创建一个lambda表达式Func<object, object>,它将其输入解包,执行所需的类型转换,然后给出结果框.不仅需要一个新的类型,而且还需要获取的类型(因为取消装箱步骤).创建这些表达式非常耗时,因为反射,编译和动态方法构建都是在幕后完成的.幸运的是,一旦创建了表达式,就可以重复调用表达式而不会产生高额开销,因此我会缓存每个表达式.
private static Func<object, object> MakeCastDelegate(Type from, Type to)
{
    var p = Expression.Parameter(typeof(object)); //do not inline
    return Expression.Lambda<Func<object, object>>(
        Expression.Convert(Expression.ConvertChecked(Expression.Convert(p, from), to), typeof(object)),
        p).Compile();
}
private static readonly Dictionary<Tuple<Type, Type>, Func<object, object>> CastCache
= new Dictionary<Tuple<Type, Type>, Func<object, object>>();
public static Func<object, object> GetCastDelegate(Type from, Type to)
{
    lock (CastCache)
    {
        var key = new Tuple<Type, Type>(from, to);
        Func<object, object> cast_delegate;
        if (!CastCache.TryGetValue(key, out cast_delegate))
        {
            cast_delegate = MakeCastDelegate(from, to);
            CastCache.Add(key, cast_delegate);
        }
        return cast_delegate;
    }
}
public static object Cast(Type t, object o)
{
    return GetCastDelegate(o.GetType(), t).Invoke(o);
}
请注意,这不是魔术.代码中不会发生转换,就像dynamic关键字一样,只转换对象的基础数据.在编译时,我们仍然需要精心确定我们的对象可能是什么类型,使得这个解决方案不切实际.我把它写成一个hack来调用由任意类型定义的转换运算符,但也许有人可以找到更好的用例.
为了简单起见,将装箱和拆箱放在一边,在继承层次结构中进行转换时没有涉及特定的运行时操作.这主要是编译时间的事情.从本质上讲,强制转换告诉编译器将变量的值视为另一种类型.
演员表演后你能做些什么?你不知道类型,所以你将无法调用任何方法.你不能做任何特别的事情.具体来说,只有在编译时知道可能的类型,手动编译并使用if语句分别处理每个案例时,它才有用:
if (type == typeof(int)) {
    int x = (int)obj;
    DoSomethingWithInt(x);
} else if (type == typeof(string)) {
    string s = (string)obj;
    DoSomethingWithString(s);
} // ...
小智 7
在使用 Zyphrax 的答案时没有找到任何解决“对象必须实现 IConvertible”异常的方法(实现接口除外)。我尝试了一些非常规的方法并适合我的情况。
使用 Newtonsoft.Json nuget 包...
var castedObject = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(myObject), myType);
你怎么能做到这一点?你需要一个T类型的变量或字段,你可以在演员之后存储对象,但是如果你只在运行时知道T,你怎么能有这样的变量或字段呢?所以,不,这是不可能的.
Type type = GetSomeType();
Object @object = GetSomeObject();
??? xyz = @object.CastTo(type); // How would you declare the variable?
xyz.??? // What methods, properties, or fields are valid here?
| 归档时间: | 
 | 
| 查看次数: | 236782 次 | 
| 最近记录: |