簡體   English   中英

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

[英]How to store a reference to an object in System.DataTable, rather than a string?

我已經寫了這個程序:

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為字符串數組,則避免這一切混亂嗎?

那是因為您添加了Column1而不指定其類型,因此默認情況下將為它分配string

嘗試將其顯式設置為Object

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

資料

您可以通過在向數據表中添加列時定義列的數據類型來避免這種情況。

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

如果您未指定column的數據類型,則默認為string 參考文章

嘗試使用此代碼,您將看到魔術。 :)

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}]?");
           }
       }
    }
}

您可以在此處運行: https : //dotnetfiddle.net/y84NCh (在線.Net編譯器)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM