2011-03-12 52 views
3

鑄造我有一個LINQ類接口,採用System.Data.Linq.Binary數據類型的類。我試圖寫一個簡單的類,它是表示存儲爲二進制數據類型的一般安排:C#泛型使用LINQ

// .Value is a System.Data.Linq.Binary DataType 
public class DataType<T> where T : class 
{ 
    public T Value 
    { 
     get 
     { 
      return from d in Database 
        where d.Value = [Some Argument Passed] 
        select d.Value as T; 
     } 
    } 
} 

public class StringClass : DataType<string> 
{ 
} 

public class ByteClass : DataType<byte[]> 
{ 
} 

威爾StringClass.Value正確施放並返回從數據庫中string

ByteClass.Value正確投射並從數據庫返回byte[]

我的主要問題基本上解決了如何使用System.Data.Linq.Binary。

編輯:如何將System.Data.Linq.Binary轉換爲T,其中T可以是任何東西。我的代碼實際上並不工作,因爲我無法使用as將Binary強制轉換爲T.

回答

1

基本上你正在做

System.Data.Linq.Binary b1; 

string str = b as string; 

System.Data.Linq.Binary b2 

byte[] bArray = b2 as byte[]; 

既海峽和bArray將是無效的;

你會需要像

public class DataType<T> where T : class 
{ 
    public T Value 
    { 
     get 
     { 
      // call ConvertFromBytes with linqBinary.ToArray() 
      // not sure about the following; you might have to tweak it. 
      return ConvertFromBytes((from d in Database 
        where d.Value = [Some Argument Passed] 
        select d.Value). 
      First().ToArray()); 
     } 
    } 

    protected virtual T ConvertFromBytes(byte[] getBytes) 
    { 
     throw new NotImplementedException(); 
    } 
} 

public class StringClass : DataType<string> 
{ 
    protected override string ConvertFromBytes(byte[] getBytes) 
    { 
     return Encoding.UTF8.GetString(getBytes); 
    }  
} 

public class ByteClass : DataType<byte[]> 
{ 
    protected override byte[] ConvertFromBytes(byte[] getBytes) 
    { 
     return getBytes; 
    } 
}