如何在System.DataTable中存储对对象的引用,而不是字符串?

杰米·威尔斯(Jamie Twells)

我已经写了这个程序:

using System;
using System.Data;

public class Program
{
    public static void Main()
    {
        using (var dt = new DataTable())
        {
            // the data in the table - one row one column
            var person = new
            {
                Name = "ABC",
                Age = 24
            };

            // setup data table
            dt.Columns.Add("Column1");
            var row = dt.NewRow();
            row["Column1"] = person;
            dt.Rows.Add(row);

            // assert
            var storedPerson = dt.Rows[0]["Column1"];

            if(!ReferenceEquals(dt.Rows[0].ItemArray[0], storedPerson))
                throw new Exception();

            if(!ReferenceEquals(storedPerson, person)){
                Console.WriteLine("What is going on?");
                Console.WriteLine($"Person is stored as a [{storedPerson.GetType().Name}]!");
                Console.WriteLine($"Why is it not of type: [{person.GetType().Name}]?");
            }
        }
    }
}

您可以在此处运行:https : //dotnetfiddle.net/LzHPs1

我期望没有异常,也没有输出,但是我实际上得到了:

What is going on?
Person is stored as a [String]!
Why is it not of type: [<>f__AnonymousType0`2]?

当对象插入行时,数据表类是否应该在对象上调用ToString()?

我可以避免它并存储对该对象的引用吗?如果可以的话,该怎么办?如果不能确定Microsoft是否可以限制行值的分配,使其只接受字符串,而索引的返回类型为字符串,而ItemArray为字符串数组,则避免这一切混乱吗?

haim770

那是因为您添加时Column1未指明其类型,因此默认情况下将对其进行分配string

尝试将其显式设置为Object

dt.Columns.Add("Column1", typeof(Object));

资料

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章