C# 如何在System.DataTable中存储对对象的引用,而不是字符串?
我写了这个程序:C# 如何在System.DataTable中存储对对象的引用,而不是字符串?,c#,.net,datatable,C#,.net,Datatable,我写了这个程序: 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
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}]?");
}
}
}
}
您可以在此处运行:
我希望没有异常和输出,但我实际得到:
What is going on?
Person is stored as a [String]!
Why is it not of type: [<>f__AnonymousType0`2]?
发生了什么事?
Person存储为[字符串]!
为什么它不是类型:[f_u匿名类型0`2]?
当对象被插入到行中时,数据表类是否应该对其调用ToString()
我可以避免它并存储对对象的引用吗?如果可以,我该怎么做?如果不能,微软可以限制行值的赋值只接受字符串,索引的返回类型为string,ItemArray为string数组,并避免所有这些混淆?这是因为您添加了
Column1
,但没有指明其类型,因此,默认情况下,它将被指定为字符串
尝试将其显式设置为对象
:
dt.Columns.Add("Column1", typeof(Object));
请参见在向数据表中添加列时,只需定义列的数据类型即可避免此问题 i、 e 如果未指定列的数据类型,则默认为字符串 尝试此代码,您将看到其神奇之处。:)
您可以在此处运行:(联机.Net编译器)在数据表中存储对象的目标是什么?我觉得您正试图解决一个问题,但这并不是解决这个问题的好方法。我只是为DataTable类编写一些帮助器方法。单元测试并没有在我预期的时候变成绿色。即使这样,OP以后也无法使用该对象,因为它是匿名类型,恐怕慢了10分钟!但是谢谢你的贡献,我感谢你抽出时间来帮助我:)我写得很慢,我在发帖后意识到有其他人先回答了。)如果这正是我想要的,那就贡献快乐编码:)
dt.Columns.Add("Column1",typeof(object));
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",typeof(object));
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}]?");
}
}
}
}