2011-03-12 44 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; 
    } 
}