我有一个没有键、顺序或其他明显索引的对象集合。
我希望将有关每个对象的数据存储在数据表中。我认为执行此操作的一种优雅方法是在所有者列中存储引用,并使该列类型为 typeof(MyClass)
。
但是,当我尝试在实践中执行此操作时,它不起作用(它说主键冲突)。事实证明,将实例放入行字段只是将“MyProgram.MyClass
”写入该字段 - 可能是 toString
的输出,即使该行的类型应该是 MyClass
而不是字符串
。
下面是一些在 LINQPad 中运行的示例代码:
void Main()
{
// Create a table
var table = new DataTable();
var ownerColumn = new DataColumn("Owner", typeof(MyClass));
var primaryKey = new[] { ownerColumn };
table.Columns.AddRange(primaryKey);
table.PrimaryKey = primaryKey;
table.Columns.Add(new DataColumn("Some Data", typeof(int)) { DefaultValue = 0 });
// Create 2 objects
var c1 = new MyClass();
var c2 = new MyClass();
// Store their data in the table
var row = table.NewRow();
row["Owner"] = c1;
row["Some Data"] = 1;
table.Rows.Add(row);
row = table.NewRow();
row["Owner"] = c2;
row["Some Data"] = 2;
table.Rows.Add(row);
}
// Define other methods and classes here
class MyClass {
}
我该怎么做才能解决这个问题?我是否必须在 MyClass
中创建一个 id
字段,然后使用 id
填写所有者列,然后确保每个对象接收一个我自己创建时唯一的id
?
最佳答案
您必须在MyClass
上实现System.IComparable
(非通用版本)接口(interface),以便DataTable
知道如何比较值列的。如果未定义此接口(interface),代码将回退到比较 object.ToString() 结果。
关于c# - 使用 "this"关键字在 DataTable 中存储对对象的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13232471/