亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C#向數(shù)據(jù)庫中插入或更新null空值與延遲加載lazy

 更新時間:2022年05月31日 14:05:47   作者:springsnow  
這篇文章介紹了C#向數(shù)據(jù)庫中插入或更新null空值與延遲加載lazy,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

插入或更新null空值

一、在SQL語句中直接插入null或空字符串“”

int? item = null;
item == null ? 
"null"
 : item.ToString();
item == null ? "" : item.ToString();

二、用命令參數(shù),插入DBNull.Value

int? item = null;
cmd.Parameters.Add(dbPams.MakeInParam(":Item", SqlNull(item)));
cmd.Parameters[0].IsNullable = true;//更新時需加入此句。

static public object SqlNull(object obj)
{
    return (item == null ? DBNull.Value : item)
}

延遲加載

.在.NET4.0中,可以使用Lazy 來實現(xiàn)對象的延遲初始化,從而優(yōu)化系統(tǒng)的性能。

正如我們所知,對象的加載是需要消耗時間的,特別是對于大對象來說消耗的時間更多.lazy可以實現(xiàn)對象的延遲加載。延時加載,意思是對象在使用的時候創(chuàng)建而不是在實例化的的時候才創(chuàng)建。

Lazy 對象初始化默認是線程安全的,在多線程環(huán)境下,第一個訪問 Lazy 對象的 Value 屬性的線程將初始化 Lazy 對象,以后訪問的線程都將使用第一次初始化的數(shù)據(jù)。

一、延時加載主要應用的場景:

  • 數(shù)據(jù)層(ADO.NET或Entity Framework等ORM,Java里面的Hibernate也用到了這種技術(shù))
  • 反射(加載assemblier,type,MEF)
  • 緩存對象,領(lǐng)域?qū)嶓w
  • 單例模式

二、簡單用法

如下:其中IsValueCreated屬相顯示其是否被創(chuàng)建。

static void Main(string[] args)
{
 Lazy lazyBig = new Lazy(); 
 Console.WriteLine("對象是否創(chuàng)建" + lazyBig.IsValueCreated);
 lazyBig.Value.Test(); 
 Console.WriteLine("對象是否創(chuàng)建" + lazyBig.IsValueCreated); 
} 

class Big {
 public Big() { } 
 public void Test() {
   Console.WriteLine("Test...."); 
}
 } //結(jié)果如下: //對象是否創(chuàng)建False //Test.... //對象是否創(chuàng)建True

由此可見,根據(jù)lazy創(chuàng)建的對象,只有當?shù)谝淮问褂玫剿鼤r才會初始化.

另,lazy可使用委托來創(chuàng)建。

static void Main(string[] args)
{
    Lazy lazyBig = new Lazy( () => new Big(100) );
    lazyBig.Value.Test();
} 

class Big { 
  public Big(int id) { this.ID = id; }
  public int ID { get; set; }
  public void Test()
    {
        Console.WriteLine("ID = " + ID.ToString());
    }
}

到此這篇關(guān)于C#向數(shù)據(jù)庫中插入或更新null空值與延遲加載lazy的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論