将值设置为基本类型的实例
我有一个执行某些操作的函数,即从数据库中获取一些数据。 它采用的泛型始终是原始类型,即 int、char、bool、string 等。我可以轻松创建它的实例。但我无法将从数据库获取的值设置到此实例。
public T PerformOperation<T>()
{
object instance = (T)Activator.CreateInstance(typeof(T));
object result=FetchData();
instance = (T)result; //It gives error on this statement
}
该函数被调用为:
int result = PerformOperation<int>();
是否有某种方法将对象类型转换为任何始终是原始类型的泛型类型?
I have a function which performs some operation i.e. fetches some data from database.
The generic it takes is primitive type always i.e. int, char, bool, string etc. I can easily create its instance. But I can't set the value that I have fetched from database to this instance.
public T PerformOperation<T>()
{
object instance = (T)Activator.CreateInstance(typeof(T));
object result=FetchData();
instance = (T)result; //It gives error on this statement
}
The function is called as:
int result = PerformOperation<int>();
Is there some way of casting the object Type to any generic type which is always primitive?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您已经拥有类型 T 时,为什么不需要将其装箱到 Object 中。
或者如果您必须使用
Object
,则可能是这种方式。When you already have type T, why box it into Object unnecessary.
or may be this way, if you must use
Object
.