簡體   English   中英

使用Linq進行C#Generic Casting

[英]C# Generic Casting with Linq

我有一個與linq類接口並使用System.Data.Linq.Binary數據類型的類。 我正在嘗試編寫一個簡單的類,它采用通用的排列方式,表示存儲為二進制的數據類型:

// .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.

基本上你在做

System.Data.Linq.Binary b1;

string str = b as string;

System.Data.Linq.Binary b2

byte[] bArray = b2 as byte[];

str和bArray都是null;

你會需要類似的東西

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;
    }
}

暫無
暫無

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

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