使用反射编写 ORM 无法正确转换

发布于 2024-12-27 11:58:00 字数 575 浏览 3 评论 0原文

所以我正在用 C# 编写一个 ORM,纯粹是为了个人学习。我正在循环访问数据库,其中列名与类的属性匹配。然后,我循环访问类的属性并分配相应的数据库列值,但我遇到了从数据库列转换返回值的问题。

var PropCollection = type.GetProperties();
foreach (PropertyInfo Property in PropCollection)
{
    Property.SetValue(_t, DReader[Property.Name].ToString(),null);
}

我收到预期的错误:

“System.String”类型的对象无法转换为类型 'System.Int32'。

其中 DReader 只是一个在循环内返回列值的 SQLDataReader,假设该值是 int,我如何将其转换为这样?

Property.GetType();

正确地知道我需要的类型,但如何使用它来转换 DReader[Property.Name]

So I am writing, strictly for personal learning, an ORM in C#. I am looping through a database, where the column names match the properties of a class. I am then looping through the properties of the class and assigning the corresponding database column values but i am running into issues casting the return value from the database column.

var PropCollection = type.GetProperties();
foreach (PropertyInfo Property in PropCollection)
{
    Property.SetValue(_t, DReader[Property.Name].ToString(),null);
}

I get the expected error:

Object of type 'System.String' cannot be converted to type
'System.Int32'.

Where DReader is just an SQLDataReader returning a column value inside of a loop, say this value is an int, how do I cast it as such??

Property.GetType();

correctly knows the type I need but how do I use that to cast DReader[Property.Name]?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

仅此而已 2025-01-03 11:58:00

Convert.ChangeType 可以处理所有直接转换。

您不应在循环中使用DReader[Property.Name].ToString()。删除ToString()

var PropCollection = type.GetProperties();
foreach (PropertyInfo Property in PropCollection)
{
    var value = DReader[Property.Name];
    if (!Property.GetType().IsAssignableFrom(value.GetType())
        value = Convert.ChangeType(value, Property.GetType());

    Property.SetValue(_t, value, null);
}

Convert.ChangeType can handle all straight conversions.

You should not use DReader[Property.Name].ToString() in your loop. Remove the ToString().

var PropCollection = type.GetProperties();
foreach (PropertyInfo Property in PropCollection)
{
    var value = DReader[Property.Name];
    if (!Property.GetType().IsAssignableFrom(value.GetType())
        value = Convert.ChangeType(value, Property.GetType());

    Property.SetValue(_t, value, null);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文