如何转换为类型传递给函数的对象? [英] How to cast an object to type passed to a function?

查看:95
本文介绍了如何转换为类型传递给函数的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这并不编译,但我想要做的仅仅是铸造对象是传递给函数'T'?



 公共无效my_func,并将(对象输入,T型)
{
(t)的对象AB = TypeDescriptor.GetConverter(T).ConvertFromString(input.ToString());
}


解决方案

您可以这样做:

 对象AB = Convert.Changetype(输入,T); 



不过,它看起来像你想使用 AB 在一个强类型的方式,你只能通过使用泛型这样做的:

 公共无效my_func,并将< T>(对象输入)
{$ b $(b T)= AB(T)Convert.ChangeType(输入的typeof(T));
}


This doesn't compile, but what I'm trying to do is simply casting object to 't' which is passed to the function?

public void My_Func(Object input, Type t)
{
   (t)object ab = TypeDescriptor.GetConverter(t).ConvertFromString(input.ToString());
}

解决方案

You could do something like:

object ab = Convert.Changetype(input, t);

however, it looks like you want to use ab in a strongly-typed manner, which you can only do so by using generics:

public void My_Func<T>(Object input)
{
   T ab = (T)Convert.ChangeType(input, typeof(T));
}

这篇关于如何转换为类型传递给函数的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆